| 1 | # fork |
| 2 | |
| 3 | [](https://crates.io/crates/fork) |
| 4 | [](https://docs.rs/fork) |
| 5 | [](https://github.com/immortal/fork/actions/workflows/build.yml) |
| 6 | [](https://coveralls.io/github/immortal/fork?branch=main) |
| 7 | [](https://github.com/immortal/fork/blob/main/LICENSE) |
| 8 | |
| 9 | Library for creating a new process detached from the controlling terminal (daemon) on Unix-like systems. |
| 10 | |
| 11 | ## Features |
| 12 | |
| 13 | - ✅ **Minimal** - Small, focused library for process forking and daemonization |
| 14 | - ✅ **Safe** - Comprehensive test coverage across all APIs and edge cases |
| 15 | - ✅ **Well-documented** - Extensive documentation with real-world examples |
| 16 | - ✅ **Unix-first** - Built specifically for Unix-like systems (Linux, macOS, BSD) |
| 17 | - ✅ **Edition 2024** - Uses latest Rust edition features |
| 18 | |
| 19 | ## Why? |
| 20 | |
| 21 | - Minimal library to daemonize, fork, double-fork a process |
| 22 | - [daemon(3)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/daemon.3.html) has been |
| 23 | deprecated in macOS 10.5. By using `fork` and `setsid` syscalls, new methods |
| 24 | can be created to achieve the same goal |
| 25 | - Provides the building blocks for creating proper Unix daemons |
| 26 | |
| 27 | ## Installation |
| 28 | |
| 29 | Add `fork` to your `Cargo.toml`: |
| 30 | |
| 31 | ```toml |
| 32 | [dependencies] |
| 33 | fork = "0.6.0" |
| 34 | ``` |
| 35 | |
| 36 | Or use cargo-add: |
| 37 | |
| 38 | ```bash |
| 39 | cargo add fork |
| 40 | ``` |
| 41 | |
| 42 | ## Quick Start |
| 43 | |
| 44 | ### Basic Daemon Example |
| 45 | |
| 46 | ```rust |
| 47 | use fork::{daemon, Fork}; |
| 48 | use std::process::Command; |
| 49 | |
| 50 | fn main() { |
| 51 | if let Ok(Fork::Child) = daemon(false, false) { |
| 52 | // This code runs in the daemon process |
| 53 | Command::new("sleep") |
| 54 | .arg("300") |
| 55 | .output() |
| 56 | .expect("failed to execute process"); |
| 57 | } |
| 58 | } |
| 59 | ``` |
| 60 | |
| 61 | ### Simple Fork Example |
| 62 | |
| 63 | ```rust |
| 64 | use fork::{fork, Fork, waitpid, WIFEXITED, WEXITSTATUS}; |
| 65 | |
| 66 | match fork() { |
| 67 | Ok(Fork::Parent(child)) => { |
| 68 | println!("Parent process, child PID: {}", child); |
| 69 | |
| 70 | // Wait for child and check exit status |
| 71 | match waitpid(child) { |
| 72 | Ok(status) => { |
| 73 | if WIFEXITED(status) { |
| 74 | println!("Child exited with code: {}", WEXITSTATUS(status)); |
| 75 | } |
| 76 | } |
| 77 | Err(e) => eprintln!("waitpid failed: {}", e), |
| 78 | } |
| 79 | } |
| 80 | Ok(Fork::Child) => { |
| 81 | println!("Child process"); |
| 82 | std::process::exit(0); |
| 83 | } |
| 84 | Err(e) => eprintln!("Fork failed: {}", e), |
| 85 | } |
| 86 | ``` |
| 87 | |
| 88 | ### Error Handling with Rich Diagnostics |
| 89 | |
| 90 | ```rust |
| 91 | use fork::{fork, Fork}; |
| 92 | |
| 93 | match fork() { |
| 94 | Ok(Fork::Parent(child)) => { |
| 95 | println!("Spawned child with PID: {}", child); |
| 96 | } |
| 97 | Ok(Fork::Child) => { |
| 98 | println!("I'm the child!"); |
| 99 | std::process::exit(0); |
| 100 | } |
| 101 | Err(err) => { |
| 102 | eprintln!("Fork failed: {}", err); |
| 103 | // Access the underlying errno if needed |
| 104 | if let Some(code) = err.raw_os_error() { |
| 105 | eprintln!("OS error code: {}", code); |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | ``` |
| 110 | |
| 111 | ## API Overview |
| 112 | |
| 113 | ### Main Functions |
| 114 | |
| 115 | - **`fork()`** - Creates a new child process |
| 116 | - **`daemon(nochdir, noclose)`** - Creates a daemon using double-fork pattern |
| 117 | - `nochdir`: if `false`, changes working directory to `/` |
| 118 | - `noclose`: if `false`, redirects stdin/stdout/stderr to `/dev/null` |
| 119 | - **`setsid()`** - Creates a new session and sets the process group ID |
| 120 | - **`waitpid(pid)`** - Waits for child process to change state (blocking; returns raw status; retries on signals) |
| 121 | - **`waitpid_nohang(pid)`** - Checks child status without blocking (returns `Option<status>`; for supervisors/polling) |
| 122 | - **`getpgrp()`** - Returns the process group ID |
| 123 | - **`getpid()`** - Returns the current process ID |
| 124 | - **`getppid()`** - Returns the parent process ID |
| 125 | - **`chdir()`** - Changes current directory to `/` |
| 126 | - **`redirect_stdio()`** - Redirects stdin/stdout/stderr to `/dev/null` (recommended) |
| 127 | - **`close_fd()`** - Closes stdin, stdout, and stderr (legacy, use `redirect_stdio()` instead) |
| 128 | |
| 129 | ### Status Inspection Macros (re-exported from libc) |
| 130 | |
| 131 | - **`WIFEXITED(status)`** - Check if child exited normally |
| 132 | - **`WEXITSTATUS(status)`** - Get exit code (if exited normally) |
| 133 | - **`WIFSIGNALED(status)`** - Check if child was terminated by signal |
| 134 | - **`WTERMSIG(status)`** - Get terminating signal (if signaled) |
| 135 | |
| 136 | See the [documentation](https://docs.rs/fork) for detailed usage. |
| 137 | |
| 138 | ## Process Tree Example |
| 139 | |
| 140 | When using `daemon(false, false)`, it will change directory to `/` and redirect stdin/stdout/stderr to `/dev/null`. |
| 141 | |
| 142 | Test running: |
| 143 | |
| 144 | ```bash |
| 145 | $ cargo run |
| 146 | ``` |
| 147 | |
| 148 | Use `ps` to check the process: |
| 149 | |
| 150 | ```bash |
| 151 | $ ps -axo ppid,pid,pgid,sess,tty,tpgid,stat,uid,%mem,%cpu,command | egrep "myapp|sleep|PID" |
| 152 | ``` |
| 153 | |
| 154 | Output: |
| 155 | |
| 156 | ``` |
| 157 | PPID PID PGID SESS TTY TPGID STAT UID %MEM %CPU COMMAND |
| 158 | 1 48738 48737 0 ?? 0 S 501 0.0 0.0 target/debug/myapp |
| 159 | 48738 48753 48737 0 ?? 0 S 501 0.0 0.0 sleep 300 |
| 160 | ``` |
| 161 | |
| 162 | Key points: |
| 163 | - `PPID == 1` - Parent is init/systemd (orphaned process) |
| 164 | - `TTY = ??` - No controlling terminal |
| 165 | - New `PGID = 48737` - Own process group |
| 166 | |
| 167 | Process hierarchy: |
| 168 | |
| 169 | ``` |
| 170 | 1 - root (init/systemd) |
| 171 | └── 48738 myapp PGID - 48737 |
| 172 | └── 48753 sleep PGID - 48737 |
| 173 | ``` |
| 174 | |
| 175 | ## Double-Fork Daemon Pattern |
| 176 | |
| 177 | The `daemon()` function implements the classic double-fork pattern: |
| 178 | |
| 179 | 1. **First fork** - Creates child process |
| 180 | 2. **setsid()** - Child becomes session leader |
| 181 | 3. **Second fork** - Grandchild is created (not a session leader) |
| 182 | 4. **First child exits** - Leaves grandchild orphaned |
| 183 | 5. **Grandchild continues** - As daemon (no controlling terminal) |
| 184 | |
| 185 | This prevents the daemon from ever acquiring a controlling terminal. |
| 186 | |
| 187 | ## Safety Notes |
| 188 | |
| 189 | - `daemon()` uses `_exit` in the forked parents to avoid running non-async-signal-safe destructors between fork/exec (POSIX-safe on Linux/macOS/BSD). |
| 190 | - `redirect_stdio()` and `close_fd()` retry on `EINTR` for `open/dup2/close` to prevent spurious failures under signal-heavy workloads. |
| 191 | - Prefer `redirect_stdio()` over `close_fd()` so file descriptors 0,1,2 stay occupied (avoids accidental log/data corruption). |
| 192 | |
| 193 | ## Testing |
| 194 | |
| 195 | Run tests: |
| 196 | |
| 197 | ```bash |
| 198 | cargo test |
| 199 | ``` |
| 200 | |
| 201 | See [`tests/README.md`](tests/README.md) for detailed information about integration tests. |
| 202 | |
| 203 | ## Platform Support |
| 204 | |
| 205 | This library is designed for Unix-like operating systems: |
| 206 | |
| 207 | - ✅ Linux |
| 208 | - ✅ macOS |
| 209 | - ✅ FreeBSD |
| 210 | - ✅ NetBSD |
| 211 | - ✅ OpenBSD |
| 212 | - ❌ Windows (not supported) |
| 213 | |
| 214 | ## Documentation |
| 215 | |
| 216 | - [API Documentation](https://docs.rs/fork) |
| 217 | - [Integration Tests Documentation](tests/README.md) |
| 218 | - [Changelog](CHANGELOG.md) |
| 219 | |
| 220 | ## Examples |
| 221 | |
| 222 | See the [`examples/`](examples/) directory for more usage examples: |
| 223 | |
| 224 | - `example_daemon.rs` - Daemon creation |
| 225 | - `example_pipe.rs` - Fork with pipe communication |
| 226 | - `example_touch_pid.rs` - PID file creation |
| 227 | |
| 228 | Run an example: |
| 229 | |
| 230 | ```bash |
| 231 | cargo run --example example_daemon |
| 232 | ``` |
| 233 | |
| 234 | ## Contributing |
| 235 | |
| 236 | Contributions are welcome! Please ensure: |
| 237 | |
| 238 | - All tests pass: `cargo test` |
| 239 | - Code is formatted: `cargo fmt` |
| 240 | - No clippy warnings: `cargo clippy -- -D warnings` |
| 241 | - Documentation is updated |
| 242 | |
| 243 | ## License |
| 244 | |
| 245 | BSD 3-Clause License - see [LICENSE](LICENSE) file for details. |