#daemon-process #process #daemon #daemonize #setsid

fork

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

25 releases

0.2.0 Jul 19, 2024
0.1.23 Feb 1, 2024
0.1.22 Jun 6, 2023
0.1.21 Mar 12, 2023
0.1.9 Oct 28, 2019

#66 in Operating systems

Download history 18119/week @ 2024-07-20 17419/week @ 2024-07-27 17512/week @ 2024-08-03 21306/week @ 2024-08-10 20051/week @ 2024-08-17 26970/week @ 2024-08-24 17843/week @ 2024-08-31 29169/week @ 2024-09-07 20980/week @ 2024-09-14 22581/week @ 2024-09-21 30001/week @ 2024-09-28 16352/week @ 2024-10-05 25917/week @ 2024-10-12 18546/week @ 2024-10-19 23099/week @ 2024-10-26 11727/week @ 2024-11-02

81,851 downloads per month
Used in 29 crates (27 directly)

BSD-3-Clause

11KB
81 lines

fork

crates.io Build codecov 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 myapp

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

Add fork as a depdendecie:

cargo add fork

or Edit myapp/Cargo.toml and add to [dependencies]:

fork = "0.1"

Add the following code to myapp/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 "myapp|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/myapp
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 myapp        PGID - 48737
      \--- 48753 sleep      PGID - 48737
    

Dependencies

~44KB