#fork #daemon #process #daemonize #setsid

fork

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

23 releases

new 0.1.22 Jun 6, 2023
0.1.21 Mar 12, 2023
0.1.20 Aug 23, 2022
0.1.19 Mar 11, 2022
0.1.9 Oct 28, 2019

#40 in Operating systems

Download history 4176/week @ 2023-02-14 4565/week @ 2023-02-21 5203/week @ 2023-02-28 4535/week @ 2023-03-07 3612/week @ 2023-03-14 5191/week @ 2023-03-21 4226/week @ 2023-03-28 4478/week @ 2023-04-04 8325/week @ 2023-04-11 7158/week @ 2023-04-18 6525/week @ 2023-04-25 4960/week @ 2023-05-02 4156/week @ 2023-05-09 3456/week @ 2023-05-16 4267/week @ 2023-05-23 4653/week @ 2023-05-30

17,671 downloads per month
Used in 18 crates (17 directly)

BSD-3-Clause

9KB
73 lines

fork

crates.io Build Status docs

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

Why?

  • Minimal library to daemonize, fork, double-fork a process.
  • daemon(3) 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

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:

 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
    

Dependencies

~39KB