File: README.md

package info (click to toggle)
rust-fork 0.1.23-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 120 kB
  • sloc: makefile: 4
file content (71 lines) | stat: -rw-r--r-- 2,207 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# fork

[![crates.io](https://img.shields.io/crates/v/fork.svg)](https://crates.io/crates/fork)
[![Build](https://github.com/immortal/fork/actions/workflows/build.yml/badge.svg)](https://github.com/immortal/fork/actions/workflows/build.yml)
[![codecov](https://codecov.io/gh/immortal/fork/graph/badge.svg?token=LHZW56OC10)](https://codecov.io/gh/immortal/fork)
[![docs](https://docs.rs/fork/badge.svg)](https://docs.rs/fork)

Library for creating a new process detached from the controlling terminal (daemon).

## Why?

- Minimal library to daemonize, fork, double-fork a process.
- [daemon(3)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/daemon.3.html) has been
deprecated in MacOSX 10.5, by using `fork` and `setsid` syscalls, new methods
can be created to achieve the same goal.

Example:

Create a new test project:

    $ cargo new --bin fork

> To install `cargo` use: `curl https://sh.rustup.rs -sSf | sh`

Edit `fork/Cargo.toml` and add to `[dependencies]`:

    fork = "0.1"

Add the following code to `fork/main.rs`

```rs
use fork::{daemon, Fork};
use std::process::Command;

fn main() {
    if let Ok(Fork::Child) = daemon(false, false) {
        Command::new("sleep")
            .arg("300")
            .output()
            .expect("failed to execute process");
    }
}
```

> If using `daemon(false, false)`,it will `chdir` to `/` and close the standard input, standard output, and standard error file descriptors.

Test running:

    $ cargo run

Use `ps` to check the process, for example:

    $ ps -axo ppid,pid,pgid,sess,tty,tpgid,stat,uid,%mem,%cpu,command, | egrep "fork|sleep|PID"

> `egrep` is used to show the `ps` headers

Output should be something like:

```pre
 PPID   PID  PGID   SESS TTY      TPGID STAT   UID       %MEM  %CPU COMMAND
    1 48738 48737      0 ??           0 S      501        0.0   0.0 target/debug/fork
48738 48753 48737      0 ??           0 S      501        0.0   0.0 sleep 300
```

* `PPID == 1` that's the parent process
* `TTY = ??` no controlling terminal
* new `PGID = 48737`

      1 - root (init/launchd)
       \-- 48738 fork         PGID - 48737
        \--- 48753 sleep      PGID - 48737