Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! Library for creating a new process detached from the controlling terminal (daemon).
2 //!
3 //! # Quick Start
4 //!
5 //! ```
6 //! use fork::{daemon, Fork};
7 //! use std::process::Command;
8 //!
9 //! if let Ok(Fork::Child) = daemon(false, false) {
10 //! Command::new("sleep")
11 //! .arg("3")
12 //! .output()
13 //! .expect("failed to execute process");
14 //! }
15 //! ```
16 //!
17 //! # Common Patterns
18 //!
19 //! ## Process Supervisor
20 //!
21 //! Track multiple worker processes:
22 //!
23 //! ```no_run
24 //! use fork::{fork, Fork, waitpid_nohang, WIFEXITED};
25 //! use std::collections::HashMap;
26 //!
27 //! # fn main() -> std::io::Result<()> {
28 //! let mut workers = HashMap::new();
29 //!
30 //! // Spawn 3 workers
31 //! for i in 0..3 {
32 //! match fork()? {
33 //! result @ Fork::Parent(_) => {
34 //! workers.insert(result, format!("worker-{}", i));
35 //! }
36 //! Fork::Child => {
37 //! // Do work...
38 //! std::thread::sleep(std::time::Duration::from_secs(5));
39 //! std::process::exit(0);
40 //! }
41 //! }
42 //! }
43 //!
44 //! // Monitor workers without blocking
45 //! while !workers.is_empty() {
46 //! workers.retain(|child, name| {
47 //! match waitpid_nohang(child.child_pid().unwrap()) {
48 //! Ok(Some(status)) if WIFEXITED(status) => {
49 //! println!("{} exited", name);
50 //! false // Remove from map
51 //! }
52 //! _ => true // Keep in map
53 //! }
54 //! });
55 //! std::thread::sleep(std::time::Duration::from_millis(100));
56 //! }
57 //! # Ok(())
58 //! # }
59 //! ```
60 //!
61 //! ## Inter-Process Communication (IPC) via Pipe
62 //!
63 //! ```no_run
64 //! use fork::{fork, Fork};
65 //! use std::io::{Read, Write};
66 //! use std::os::unix::io::FromRawFd;
67 //!
68 //! # fn main() -> std::io::Result<()> {
69 //! // Create pipe before forking
70 //! let mut pipe_fds = [0i32; 2];
71 //! unsafe { libc::pipe(pipe_fds.as_mut_ptr()) };
72 //!
73 //! match fork()? {
74 //! Fork::Parent(_child) => {
75 //! unsafe { libc::close(pipe_fds[1]) }; // Close write end
76 //!
77 //! let mut reader = unsafe { std::fs::File::from_raw_fd(pipe_fds[0]) };
78 //! let mut msg = String::new();
79 //! reader.read_to_string(&mut msg)?;
80 //! println!("Received: {}", msg);
81 //! }
82 //! Fork::Child => {
83 //! unsafe { libc::close(pipe_fds[0]) }; // Close read end
84 //!
85 //! let mut writer = unsafe { std::fs::File::from_raw_fd(pipe_fds[1]) };
86 //! writer.write_all(b"Hello from child!")?;
87 //! std::process::exit(0);
88 //! }
89 //! }
90 //! # Ok(())
91 //! # }
92 //! ```
93 //!
94 //! ## Daemon with PID File
95 //!
96 //! ```no_run
97 //! use fork::{daemon, Fork, getpid};
98 //! use std::fs::File;
99 //! use std::io::Write;
100 //!
101 //! # fn main() -> std::io::Result<()> {
102 //! if let Ok(Fork::Child) = daemon(false, false) {
103 //! // Write PID file
104 //! let pid = getpid();
105 //! let mut file = File::create("/var/run/myapp.pid")?;
106 //! writeln!(file, "{}", pid)?;
107 //!
108 //! // Run daemon logic...
109 //! loop {
110 //! // Do work
111 //! std::thread::sleep(std::time::Duration::from_secs(60));
112 //! }
113 //! }
114 //! # Ok(())
115 //! # }
116 //! ```
117 //!
118 //! # Safety and Best Practices
119 //!
120 //! - **Always check fork result** - Functions marked `#[must_use]` prevent accidents
121 //! - **Use `waitpid()`** - Reap child processes to avoid zombies
122 //! - **Prefer `redirect_stdio()`** - Safer than `close_fd()` for daemons
123 //! - **Fork early** - Before creating threads, locks, or complex state
124 //! - **Close unused file descriptors** - Prevent resource leaks in children
125 //! - **Handle signals properly** - Consider what happens in both processes
126 //!
127 //! # Platform Compatibility
128 //!
129 //! This library uses POSIX system calls and is designed for Unix-like systems:
130 //! - Linux (all distributions)
131 //! - macOS (10.5+, replacement for deprecated `daemon(3)`)
132 //! - FreeBSD, OpenBSD, NetBSD
133 //! - Other POSIX-compliant systems
134 //!
135 //! Windows is **not supported** as it lacks `fork()` system call.
136
137 use std::io;
138
139 // Re-export libc status inspection macros for convenience
140 // This allows users to write `use fork::{waitpid, WIFEXITED, WEXITSTATUS}`
141 // instead of importing from libc separately
142 pub use libc::{WEXITSTATUS, WIFEXITED, WIFSIGNALED, WTERMSIG};
143
144 /// Fork result
145 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
146 pub enum Fork {
147 Parent(libc::pid_t),
148 Child,
149 }
150
151 /// Close a file descriptor, retrying on `EINTR` and treating `EBADF` as success.
152 #[inline]
153 fn close_retry(fd: libc::c_int) -> io::Result<()> {
154 loop {
155 let res = unsafe { libc::close(fd) };
156 if res == 0 {
157 return Ok(());
158 }
159
160 let err = io::Error::last_os_error();
161
162 if err.kind() == io::ErrorKind::Interrupted {
163 continue;
164 }
165
166 if err.raw_os_error() == Some(libc::EBADF) {
167 return Ok(());
168 }
169
170 return Err(err);
171 }
172 }
173
174 impl Fork {
175 /// Returns `true` if this is the parent process
176 ///
177 /// # Examples
178 ///
179 /// ```
180 /// use fork::{fork, Fork};
181 ///
182 /// match fork() {
183 /// Ok(result) => {
184 /// if result.is_parent() {
185 /// println!("I'm the parent");
186 /// }
187 /// }
188 /// Err(_) => {}
189 /// }
190 /// ```
191 #[must_use]
192 #[inline]
193 pub const fn is_parent(&self) -> bool {
194 matches!(self, Self::Parent(_))
195 }
196
197 /// Returns `true` if this is the child process
198 ///
199 /// # Examples
200 ///
201 /// ```
202 /// use fork::{fork, Fork};
203 ///
204 /// match fork() {
205 /// Ok(result) => {
206 /// if result.is_child() {
207 /// println!("I'm the child");
208 /// std::process::exit(0);
209 /// }
210 /// }
211 /// Err(_) => {}
212 /// }
213 /// ```
214 #[must_use]
215 #[inline]
216 pub const fn is_child(&self) -> bool {
217 matches!(self, Self::Child)
218 }
219
220 /// Returns the child PID if this is the parent, otherwise `None`
221 ///
222 /// # Examples
223 ///
224 /// ```
225 /// use fork::{fork, Fork};
226 ///
227 /// match fork() {
228 /// Ok(result) => {
229 /// if let Some(child_pid) = result.child_pid() {
230 /// println!("Child PID: {}", child_pid);
231 /// }
232 /// }
233 /// Err(_) => {}
234 /// }
235 /// ```
236 #[must_use]
237 #[inline]
238 pub const fn child_pid(&self) -> Option<libc::pid_t> {
239 match self {
240 Self::Parent(pid) => Some(*pid),
241 Self::Child => None,
242 }
243 }
244 }
245
246 /// Change dir to `/` [see chdir(2)](https://www.freebsd.org/cgi/man.cgi?query=chdir&sektion=2)
247 ///
248 /// Upon successful completion, the current working directory is changed to `/`.
249 /// Otherwise, an error is returned with the system error code.
250 ///
251 /// Example:
252 ///
253 ///```
254 ///use fork::chdir;
255 ///use std::env;
256 ///
257 ///match chdir() {
258 /// Ok(_) => {
259 /// let path = env::current_dir().expect("failed current_dir");
260 /// assert_eq!(Some("/"), path.to_str());
261 /// }
262 /// Err(e) => eprintln!("Failed to change directory: {}", e),
263 ///}
264 ///```
265 ///
266 /// # Errors
267 /// Returns an [`io::Error`] if the system call fails. Common errors include:
268 /// - Permission denied
269 /// - Path does not exist
270 ///
271 #[inline]
272 pub fn chdir() -> io::Result<()> {
273 // SAFETY: c"/" is a valid null-terminated C string literal
274 let res = unsafe { libc::chdir(c"/".as_ptr()) };
275
276 match res {
277 -1 => Err(io::Error::last_os_error()),
278 _ => Ok(()),
279 }
280 }
281
282 /// Close file descriptors stdin, stdout, stderr
283 ///
284 /// **Warning:** This function closes the file descriptors, making them
285 /// available for reuse. If your daemon opens files after calling this,
286 /// those files may get fd 0, 1, or 2, causing `println!`, `eprintln!`,
287 /// or panic output to corrupt them.
288 ///
289 /// **Use [`redirect_stdio()`] instead**, which is safer and follows
290 /// industry best practices by redirecting stdio to `/dev/null` instead
291 /// of closing. This keeps fd 0, 1, 2 occupied, ensuring subsequent files
292 /// get fd >= 3, preventing silent corruption.
293 ///
294 /// # Errors
295 /// Returns an [`io::Error`] if any of the file descriptors fail to close.
296 /// Already-closed descriptors (`EBADF`) are treated as success so the
297 /// function is idempotent.
298 ///
299 /// # Example
300 ///
301 /// ```no_run
302 /// use fork::close_fd;
303 ///
304 /// // Warning: Files opened after this may get fd 0,1,2!
305 /// close_fd()?;
306 /// # Ok::<(), std::io::Error>(())
307 /// ```
308 pub fn close_fd() -> io::Result<()> {
309 for fd in 0..=2 {
310 close_retry(fd)?;
311 }
312
313 Ok(())
314 }
315
316 /// Redirect stdin, stdout, stderr to /dev/null
317 ///
318 /// This is the recommended way to detach from the controlling terminal
319 /// in daemon processes. Unlike [`close_fd()`], this keeps file descriptors
320 /// 0, 1, 2 occupied (pointing to /dev/null), preventing them from being
321 /// reused by subsequent `open()` calls.
322 ///
323 /// This prevents bugs where `println!`, `eprintln!`, or panic output
324 /// accidentally writes to data files that happened to get assigned fd 0, 1, or 2.
325 ///
326 /// # Implementation
327 ///
328 /// This function:
329 /// 1. Opens `/dev/null` with `O_RDWR`
330 /// 2. Uses `dup2()` to redirect fds 0, 1, 2 to `/dev/null`
331 /// 3. Closes the extra file descriptor if it was > 2
332 ///
333 /// This is the same approach used by libuv, systemd, and BSD `daemon(3)`.
334 ///
335 /// # Errors
336 ///
337 /// Returns an [`io::Error`] if:
338 /// - `/dev/null` cannot be opened
339 /// - `dup2()` fails to redirect any of the file descriptors
340 ///
341 /// # Example
342 ///
343 /// ```no_run
344 /// use fork::redirect_stdio;
345 /// use std::fs::File;
346 ///
347 /// redirect_stdio()?;
348 ///
349 /// // Now safe: files will get fd >= 3
350 /// let log = File::create("app.log")?;
351 ///
352 /// // This goes to /dev/null (safely discarded), not to app.log
353 /// println!("debug message");
354 /// # Ok::<(), std::io::Error>(())
355 /// ```
356 pub fn redirect_stdio() -> io::Result<()> {
357 let null_fd = loop {
358 let fd = unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_RDWR) };
359 if fd == -1 {
360 let err = io::Error::last_os_error();
361 if err.kind() == io::ErrorKind::Interrupted {
362 continue;
363 }
364 return Err(err);
365 }
366 break fd;
367 };
368
369 // Redirect stdin, stdout, stderr to /dev/null
370 for fd in 0..=2 {
371 loop {
372 if unsafe { libc::dup2(null_fd, fd) } == -1 {
373 let err = io::Error::last_os_error();
374 if err.kind() == io::ErrorKind::Interrupted {
375 continue;
376 }
377 // Only close null_fd if it's > 2 (not one of the stdio fds we're duplicating to)
378 // If null_fd was 0, 1, or 2, we're in the process of duping it, so don't close
379 if null_fd > 2 {
380 let _ = close_retry(null_fd);
381 }
382 return Err(err);
383 }
384 break;
385 }
386 }
387
388 // Close the extra fd if it's > 2
389 // (if null_fd was 0, 1, or 2, it's now dup'd to all three, so don't close)
390 if null_fd > 2 {
391 close_retry(null_fd)?;
392 }
393
394 Ok(())
395 }
396
397 /// Create a new child process [see fork(2)](https://www.freebsd.org/cgi/man.cgi?fork)
398 ///
399 /// Upon successful completion, `fork()` returns [`Fork::Child`] in the child process
400 /// and `Fork::Parent(pid)` with the child's process ID in the parent process.
401 ///
402 /// Example:
403 ///
404 /// ```
405 ///use fork::{fork, Fork};
406 ///
407 ///match fork() {
408 /// Ok(Fork::Parent(child)) => {
409 /// println!("Continuing execution in parent process, new child has pid: {}", child);
410 /// }
411 /// Ok(Fork::Child) => println!("I'm a new child process"),
412 /// Err(e) => eprintln!("Fork failed: {}", e),
413 ///}
414 ///```
415 /// This will print something like the following (order indeterministic).
416 ///
417 /// ```text
418 /// Continuing execution in parent process, new child has pid: 1234
419 /// I'm a new child process
420 /// ```
421 ///
422 /// The thing to note is that you end up with two processes continuing execution
423 /// immediately after the fork call but with different match arms.
424 ///
425 /// # Safety Considerations
426 ///
427 /// After calling `fork()`, the child process is an exact copy of the parent process.
428 /// However, there are important safety considerations:
429 ///
430 /// - **File Descriptors**: Inherited from parent but share the same file offset and status flags.
431 /// Changes in one process affect the other.
432 /// - **Mutexes and Locks**: May be in an inconsistent state in the child. Only the thread that
433 /// called `fork()` exists in the child; other threads disappear mid-execution, potentially
434 /// leaving mutexes locked.
435 /// - **Async-Signal-Safety**: Between `fork()` and `exec()`, only async-signal-safe functions
436 /// should be called. This includes most system calls but excludes most library functions,
437 /// memory allocation, and I/O operations.
438 /// - **Signal Handlers**: Inherited from parent but should be used carefully in multi-threaded programs.
439 /// - **Memory**: Child gets a copy-on-write copy of parent's memory. Large memory usage can impact performance.
440 ///
441 /// For detailed information, see the [fork(2) man page](https://man7.org/linux/man-pages/man2/fork.2.html).
442 ///
443 /// # [`nix::unistd::fork`](https://docs.rs/nix/0.15.0/nix/unistd/fn.fork.html)
444 ///
445 /// The example has been taken from the [`nix::unistd::fork`](https://docs.rs/nix/0.15.0/nix/unistd/fn.fork.html),
446 /// please check the [Safety](https://docs.rs/nix/0.15.0/nix/unistd/fn.fork.html#safety) section
447 ///
448 /// # Errors
449 /// Returns an [`io::Error`] if the fork system call fails. Common errors include:
450 /// - Resource temporarily unavailable (EAGAIN) - process limit reached
451 /// - Out of memory (ENOMEM)
452 #[must_use = "fork result must be checked to determine parent/child"]
453 pub fn fork() -> io::Result<Fork> {
454 let res = unsafe { libc::fork() };
455 match res {
456 -1 => Err(io::Error::last_os_error()),
457 0 => Ok(Fork::Child),
458 res => Ok(Fork::Parent(res)),
459 }
460 }
461
462 /// Wait for process to change status [see wait(2)](https://man.freebsd.org/cgi/man.cgi?waitpid)
463 ///
464 /// # Behavior
465 /// - Retries automatically on `EINTR` (interrupted by signal)
466 /// - Returns the raw status (use `libc::WIFEXITED`, `libc::WEXITSTATUS`, etc.)
467 ///
468 /// # Errors
469 /// Returns an [`io::Error`] if the waitpid system call fails. Common errors include:
470 /// - No child process exists with the given PID
471 /// - Invalid options or PID
472 ///
473 /// Example:
474 ///
475 /// ```
476 ///use fork::{waitpid, Fork};
477 ///
478 ///fn main() {
479 /// match fork::fork() {
480 /// Ok(Fork::Parent(pid)) => {
481 /// println!("Child pid: {pid}");
482 /// match waitpid(pid) {
483 /// Ok(status) => println!("Child exited with status: {status}"),
484 /// Err(e) => eprintln!("Failed to wait on child: {e}"),
485 /// }
486 /// }
487 /// Ok(Fork::Child) => {
488 /// // Child does trivial work then exits
489 /// std::process::exit(0);
490 /// }
491 /// Err(e) => eprintln!("Failed to fork: {e}"),
492 /// }
493 ///}
494 ///```
495 pub fn waitpid(pid: libc::pid_t) -> io::Result<libc::c_int> {
496 let mut status: libc::c_int = 0;
497 loop {
498 // SAFETY: &raw mut status provides a raw pointer to initialized memory
499 let res = unsafe { libc::waitpid(pid, &raw mut status, 0) };
500
501 if res == -1 {
502 let err = io::Error::last_os_error();
503
504 if err.kind() == io::ErrorKind::Interrupted {
505 continue;
506 }
507
508 return Err(err);
509 }
510
511 return Ok(status);
512 }
513 }
514
515 /// Wait for process to change status without blocking [see wait(2)](https://man.freebsd.org/cgi/man.cgi?waitpid)
516 ///
517 /// This is the non-blocking variant of [`waitpid()`]. It checks if the child has
518 /// changed status and returns immediately without blocking.
519 ///
520 /// # Return Value
521 /// - `Ok(Some(status))` - Child has exited/stopped with the given status
522 /// - `Ok(None)` - Child is still running (no state change)
523 /// - `Err(...)` - Error occurred (e.g., ECHILD if child doesn't exist)
524 ///
525 /// # Behavior
526 /// - Returns immediately (does not block)
527 /// - Retries automatically on `EINTR` (interrupted by signal)
528 /// - Returns the raw status (use `libc::WIFEXITED`, `libc::WEXITSTATUS`, etc.)
529 ///
530 /// # Use Cases
531 /// - **Process supervisors** - Monitor multiple children without blocking
532 /// - **Event loops** - Check child status while handling other events
533 /// - **Polling patterns** - Parent has other work to do while child runs
534 /// - **Non-blocking checks** - Determine if child is still running
535 ///
536 /// # Example
537 ///
538 /// ```
539 /// use fork::{fork, Fork, waitpid_nohang};
540 /// use std::time::Duration;
541 ///
542 /// match fork::fork() {
543 /// Ok(Fork::Parent(child)) => {
544 /// // Do work while child runs
545 /// for i in 0..5 {
546 /// println!("Parent working... iteration {}", i);
547 /// std::thread::sleep(Duration::from_millis(100));
548 ///
549 /// match waitpid_nohang(child) {
550 /// Ok(Some(status)) => {
551 /// println!("Child exited with status: {}", status);
552 /// break;
553 /// }
554 /// Ok(None) => {
555 /// println!("Child still running...");
556 /// }
557 /// Err(e) => {
558 /// eprintln!("Error checking child: {}", e);
559 /// break;
560 /// }
561 /// }
562 /// }
563 /// }
564 /// Ok(Fork::Child) => {
565 /// // Child does work
566 /// std::thread::sleep(Duration::from_millis(250));
567 /// std::process::exit(0);
568 /// }
569 /// Err(e) => eprintln!("Fork failed: {}", e),
570 /// }
571 /// ```
572 ///
573 /// # Errors
574 /// Returns an [`io::Error`] if the waitpid system call fails. Common errors include:
575 /// - No child process exists with the given PID (ECHILD)
576 /// - Invalid options or PID
577 pub fn waitpid_nohang(pid: libc::pid_t) -> io::Result<Option<libc::c_int>> {
578 let mut status: libc::c_int = 0;
579 loop {
580 // SAFETY: &raw mut status provides a raw pointer to initialized memory
581 let res = unsafe { libc::waitpid(pid, &raw mut status, libc::WNOHANG) };
582
583 if res == 0 {
584 // Child has not changed state (still running)
585 return Ok(None);
586 }
587
588 if res == -1 {
589 let err = io::Error::last_os_error();
590
591 if err.kind() == io::ErrorKind::Interrupted {
592 continue; // Retry on EINTR
593 }
594
595 return Err(err);
596 }
597
598 // Child changed state (exited, stopped, continued, etc.)
599 return Ok(Some(status));
600 }
601 }
602
603 /// Create session and set process group ID [see setsid(2)](https://www.freebsd.org/cgi/man.cgi?setsid)
604 ///
605 /// Upon successful completion, the `setsid()` system call returns the value of the
606 /// process group ID of the new process group, which is the same as the process ID
607 /// of the calling process.
608 ///
609 /// # Errors
610 /// Returns an [`io::Error`] if the setsid system call fails. Common errors include:
611 /// - The calling process is already a process group leader (EPERM)
612 ///
613 /// # Example
614 ///
615 /// ```
616 /// use fork::{fork, Fork, setsid};
617 ///
618 /// match fork::fork() {
619 /// Ok(Fork::Parent(child)) => {
620 /// println!("Parent process, child PID: {}", child);
621 /// }
622 /// Ok(Fork::Child) => {
623 /// // Create new session
624 /// match setsid() {
625 /// Ok(sid) => {
626 /// println!("New session ID: {}", sid);
627 /// std::process::exit(0);
628 /// }
629 /// Err(e) => {
630 /// eprintln!("Failed to create session: {}", e);
631 /// std::process::exit(1);
632 /// }
633 /// }
634 /// }
635 /// Err(e) => eprintln!("Fork failed: {}", e),
636 /// }
637 /// ```
638 #[inline]
639 #[must_use = "session ID should be used or checked for errors"]
640 pub fn setsid() -> io::Result<libc::pid_t> {
641 let res = unsafe { libc::setsid() };
642
643 match res {
644 -1 => Err(io::Error::last_os_error()),
645 res => Ok(res),
646 }
647 }
648
649 /// Get the process group ID of the current process [see getpgrp(2)](https://www.freebsd.org/cgi/man.cgi?query=getpgrp)
650 ///
651 /// Returns the process group ID of the calling process. This function is always successful
652 /// and cannot fail according to POSIX specification.
653 ///
654 /// # Example
655 ///
656 /// ```
657 /// use fork::getpgrp;
658 ///
659 /// let pgid = getpgrp();
660 /// println!("Current process group ID: {}", pgid);
661 /// ```
662 #[inline]
663 #[must_use = "process group ID should be used"]
664 pub fn getpgrp() -> libc::pid_t {
665 // SAFETY: getpgrp() has no preconditions and always succeeds per POSIX
666 unsafe { libc::getpgrp() }
667 }
668
669 /// Get the current process ID [see getpid(2)](https://man.freebsd.org/cgi/man.cgi?getpid)
670 ///
671 /// Returns the process ID of the calling process. This function is always successful.
672 ///
673 /// # Example
674 ///
675 /// ```
676 /// use fork::getpid;
677 ///
678 /// let my_pid = getpid();
679 /// println!("My process ID: {}", my_pid);
680 /// ```
681 #[inline]
682 #[must_use = "process ID should be used"]
683 pub fn getpid() -> libc::pid_t {
684 // SAFETY: getpid() has no preconditions and always succeeds
685 unsafe { libc::getpid() }
686 }
687
688 /// Get the parent process ID [see getppid(2)](https://man.freebsd.org/cgi/man.cgi?getppid)
689 ///
690 /// Returns the process ID of the parent of the calling process. This function is always successful.
691 ///
692 /// # Example
693 ///
694 /// ```
695 /// use fork::getppid;
696 ///
697 /// let parent_pid = getppid();
698 /// println!("My parent's process ID: {}", parent_pid);
699 /// ```
700 #[inline]
701 #[must_use = "process ID should be used"]
702 pub fn getppid() -> libc::pid_t {
703 // SAFETY: getppid() has no preconditions and always succeeds
704 unsafe { libc::getppid() }
705 }
706
707 /// The daemon function is for programs wishing to detach themselves from the
708 /// controlling terminal and run in the background as system daemons.
709 ///
710 /// * `nochdir = false`, changes the current working directory to the root (`/`).
711 /// * `noclose = false`, redirects stdin, stdout, and stderr to `/dev/null`
712 ///
713 /// # Implementation (double-fork)
714 ///
715 /// 1. **First fork** - Parent exits immediately.
716 /// 2. **Session setup** - Child calls `setsid()`, optionally `chdir("/")`, and optionally redirects stdio.
717 /// 3. **Second (double) fork** - Session-leader child exits immediately.
718 /// 4. **Daemon continues** - Grandchild (daemon) runs with no controlling terminal.
719 ///
720 /// # Behavior Change in v0.4.0
721 ///
722 /// Previously, `noclose = false` would close stdio file descriptors.
723 /// Now it redirects them to `/dev/null` instead, which is safer and prevents
724 /// file descriptor reuse bugs. This matches industry standard implementations
725 /// (libuv, systemd, BSD daemon(3)).
726 ///
727 /// # Errors
728 /// Returns an [`io::Error`] if any of the underlying system calls fail:
729 /// - fork fails (e.g., resource limits)
730 /// - setsid fails (e.g., already a session leader)
731 /// - chdir fails (when `nochdir` is false)
732 /// - `redirect_stdio` fails (when `noclose` is false)
733 ///
734 /// Example:
735 ///
736 ///```
737 ///// The parent forks the child
738 ///// The parent exits
739 ///// The child calls setsid() to start a new session with no controlling terminals
740 ///// The child forks a grandchild
741 ///// The child exits
742 ///// The grandchild is now the daemon
743 ///use fork::{daemon, Fork};
744 ///use std::process::Command;
745 ///
746 ///if let Ok(Fork::Child) = daemon(false, false) {
747 /// Command::new("sleep")
748 /// .arg("3")
749 /// .output()
750 /// .expect("failed to execute process");
751 ///}
752 ///```
753 #[must_use = "daemon result must be checked to determine if this is the daemon process"]
754 pub fn daemon(nochdir: bool, noclose: bool) -> io::Result<Fork> {
755 // 1. First fork: detach from original parent; parent exits immediately
756 match fork()? {
757 // SAFETY: _exit is async-signal-safe and avoids running any Rust/CRT destructors
758 Fork::Parent(_) => unsafe { libc::_exit(0) },
759 Fork::Child => {
760 // 2. Session setup in first child
761 setsid()?;
762 if !nochdir {
763 chdir()?;
764 }
765 if !noclose {
766 redirect_stdio()?;
767 }
768
769 // 3. Second Fork (Double-fork): drop session leader, keep only the daemon
770 match fork()? {
771 // SAFETY: _exit avoids invoking non-async-signal-safe destructors in the forked process
772 Fork::Parent(_) => unsafe { libc::_exit(0) },
773 Fork::Child => Ok(Fork::Child),
774 }
775 }
776 }
777 }
778
779 #[cfg(test)]
780 #[allow(clippy::expect_used)]
781 #[allow(clippy::panic)]
782 #[allow(clippy::match_wild_err_arm)]
783 #[allow(clippy::ignored_unit_patterns)]
784 #[allow(clippy::uninlined_format_args)]
785 mod tests {
786 use super::*;
787 use libc::{WEXITSTATUS, WIFEXITED};
788 use std::{
789 env,
790 os::unix::io::FromRawFd,
791 process::{Command, exit},
792 };
793
794 #[test]
795 fn test_fork() {
796 match fork() {
797 Ok(Fork::Parent(child)) => {
798 assert!(child > 0);
799 // Wait for child to complete
800 let status = waitpid(child).expect("waitpid failed");
801 assert!(WIFEXITED(status));
802 }
803 Ok(Fork::Child) => {
804 // Child process exits immediately
805 exit(0);
806 }
807 Err(_) => panic!("Fork failed"),
808 }
809 }
810
811 #[test]
812 fn test_fork_with_waitpid() {
813 match fork() {
814 Ok(Fork::Parent(child)) => {
815 assert!(child > 0);
816 let status = waitpid(child).expect("waitpid failed");
817 assert!(WIFEXITED(status));
818 assert_eq!(WEXITSTATUS(status), 0);
819 }
820 Ok(Fork::Child) => {
821 let _ = Command::new("true").output();
822 exit(0);
823 }
824 Err(_) => panic!("Fork failed"),
825 }
826 }
827
828 #[test]
829 fn test_chdir() {
830 match fork() {
831 Ok(Fork::Parent(child)) => {
832 let status = waitpid(child).expect("waitpid failed");
833 assert!(WIFEXITED(status));
834 }
835 Ok(Fork::Child) => {
836 // Test changing directory to root
837 match chdir() {
838 Ok(_) => {
839 let path = env::current_dir().expect("failed current_dir");
840 assert_eq!(Some("/"), path.to_str());
841 exit(0);
842 }
843 Err(_) => exit(1),
844 }
845 }
846 Err(_) => panic!("Fork failed"),
847 }
848 }
849
850 #[test]
851 fn test_getpgrp() {
852 match fork() {
853 Ok(Fork::Parent(child)) => {
854 let status = waitpid(child).expect("waitpid failed");
855 assert!(WIFEXITED(status));
856 }
857 Ok(Fork::Child) => {
858 // Get process group and verify it's valid
859 let pgrp = getpgrp();
860 assert!(pgrp > 0);
861 exit(0);
862 }
863 Err(_) => panic!("Fork failed"),
864 }
865 }
866
867 #[test]
868 fn test_setsid() {
869 match fork() {
870 Ok(Fork::Parent(child)) => {
871 let status = waitpid(child).expect("waitpid failed");
872 assert!(WIFEXITED(status));
873 }
874 Ok(Fork::Child) => {
875 // Create new session
876 match setsid() {
877 Ok(sid) => {
878 assert!(sid > 0);
879 // Verify we're the session leader
880 let pgrp = getpgrp();
881 assert_eq!(sid, pgrp);
882 exit(0);
883 }
884 Err(_) => exit(1),
885 }
886 }
887 Err(_) => panic!("Fork failed"),
888 }
889 }
890
891 #[test]
892 fn test_daemon_pattern_with_chdir() {
893 // Test the daemon pattern manually without calling daemon()
894 // to avoid exit(0) killing the test process
895 match fork() {
896 Ok(Fork::Parent(child)) => {
897 // Parent waits for child
898 let status = waitpid(child).expect("waitpid failed");
899 assert!(WIFEXITED(status));
900 }
901 Ok(Fork::Child) => {
902 // Child creates new session and forks again
903 setsid().expect("Failed to setsid");
904 chdir().expect("Failed to chdir");
905
906 match fork() {
907 Ok(Fork::Parent(_)) => {
908 // Middle process exits
909 exit(0);
910 }
911 Ok(Fork::Child) => {
912 // Grandchild (daemon) - verify state
913 let path = env::current_dir().expect("failed current_dir");
914 assert_eq!(Some("/"), path.to_str());
915
916 let pgrp = getpgrp();
917 assert!(pgrp > 0);
918
919 exit(0);
920 }
921 Err(_) => exit(1),
922 }
923 }
924 Err(_) => panic!("Fork failed"),
925 }
926 }
927
928 #[test]
929 fn test_daemon_pattern_no_chdir() {
930 // Test daemon pattern preserving current directory
931 let original_dir = env::current_dir().expect("failed to get current dir");
932
933 match fork() {
934 Ok(Fork::Parent(child)) => {
935 let status = waitpid(child).expect("waitpid failed");
936 assert!(WIFEXITED(status));
937 }
938 Ok(Fork::Child) => {
939 setsid().expect("Failed to setsid");
940 // Don't call chdir - preserve directory
941
942 match fork() {
943 Ok(Fork::Parent(_)) => exit(0),
944 Ok(Fork::Child) => {
945 let current_dir = env::current_dir().expect("failed current_dir");
946 // Directory should be preserved
947 if original_dir.to_str() != Some("/") {
948 assert!(current_dir.to_str().is_some());
949 }
950 exit(0);
951 }
952 Err(_) => exit(1),
953 }
954 }
955 Err(_) => panic!("Fork failed"),
956 }
957 }
958
959 #[test]
960 fn test_daemon_pattern_with_close_fd() {
961 // Test daemon pattern with file descriptor closure
962 match fork() {
963 Ok(Fork::Parent(child)) => {
964 let status = waitpid(child).expect("waitpid failed");
965 assert!(WIFEXITED(status));
966 }
967 Ok(Fork::Child) => {
968 setsid().expect("Failed to setsid");
969 chdir().expect("Failed to chdir");
970 close_fd().expect("Failed to close fd");
971
972 match fork() {
973 Ok(Fork::Parent(_)) => exit(0),
974 Ok(Fork::Child) => {
975 // Daemon process with closed fds
976 exit(0);
977 }
978 Err(_) => exit(1),
979 }
980 }
981 Err(_) => panic!("Fork failed"),
982 }
983 }
984
985 #[test]
986 fn test_close_fd_functionality() {
987 match fork() {
988 Ok(Fork::Parent(child)) => {
989 let status = waitpid(child).expect("waitpid failed");
990 assert!(WIFEXITED(status));
991 }
992 Ok(Fork::Child) => {
993 // Close standard file descriptors
994 match close_fd() {
995 Ok(_) => exit(0),
996 Err(_) => exit(1),
997 }
998 }
999 Err(_) => panic!("Fork failed"),
1000 }
1001 }
1002
1003 #[test]
1004 fn test_close_fd_idempotent() {
1005 match fork() {
1006 Ok(Fork::Parent(child)) => {
1007 let status = waitpid(child).expect("waitpid failed");
1008 assert!(WIFEXITED(status));
1009 assert_eq!(WEXITSTATUS(status), 0);
1010 }
1011 Ok(Fork::Child) => {
1012 // First close should succeed
1013 close_fd().expect("first close_fd failed");
1014 // Second close should treat EBADF as success
1015 close_fd().expect("second close_fd failed");
1016 exit(0);
1017 }
1018 Err(_) => panic!("Fork failed"),
1019 }
1020 }
1021
1022 #[test]
1023 fn test_double_fork_pattern() {
1024 // Test the double-fork pattern commonly used for daemons
1025 match fork() {
1026 Ok(Fork::Parent(child1)) => {
1027 assert!(child1 > 0);
1028 let status = waitpid(child1).expect("waitpid failed");
1029 assert!(WIFEXITED(status));
1030 }
1031 Ok(Fork::Child) => {
1032 // First child creates new session
1033 setsid().expect("Failed to setsid");
1034
1035 // Second fork to ensure we're not session leader
1036 match fork() {
1037 Ok(Fork::Parent(_)) => {
1038 // First child exits
1039 exit(0);
1040 }
1041 Ok(Fork::Child) => {
1042 // Grandchild - the daemon process
1043 let pgrp = getpgrp();
1044 assert!(pgrp > 0);
1045 exit(0);
1046 }
1047 Err(_) => exit(1),
1048 }
1049 }
1050 Err(_) => panic!("Fork failed"),
1051 }
1052 }
1053
1054 #[test]
1055 fn test_waitpid_with_child() {
1056 match fork() {
1057 Ok(Fork::Parent(child)) => {
1058 assert!(child > 0);
1059 // Wait for child with timeout to prevent hanging
1060 // Simple approach: just call waitpid, the child exits immediately
1061 let status = waitpid(child).expect("waitpid failed");
1062 assert!(WIFEXITED(status));
1063 }
1064 Ok(Fork::Child) => {
1065 // Child exits immediately to prevent any hanging issues
1066 exit(0);
1067 }
1068 Err(_) => panic!("Fork failed"),
1069 }
1070 }
1071
1072 #[test]
1073 fn test_fork_child_execution() {
1074 match fork() {
1075 Ok(Fork::Parent(child)) => {
1076 assert!(child > 0);
1077 // Wait for child to finish its work
1078 let status = waitpid(child).expect("waitpid failed");
1079 assert!(WIFEXITED(status));
1080 }
1081 Ok(Fork::Child) => {
1082 // Child executes a simple command
1083 let output = Command::new("echo")
1084 .arg("test")
1085 .output()
1086 .expect("Failed to execute command");
1087 assert!(output.status.success());
1088 exit(0);
1089 }
1090 Err(_) => panic!("Fork failed"),
1091 }
1092 }
1093
1094 #[test]
1095 fn test_multiple_forks() {
1096 // Test creating multiple child processes
1097 for i in 0..3 {
1098 match fork() {
1099 Ok(Fork::Parent(child)) => {
1100 assert!(child > 0);
1101 let status = waitpid(child).expect("waitpid failed");
1102 assert!(WIFEXITED(status));
1103 assert_eq!(WEXITSTATUS(status), i);
1104 }
1105 Ok(Fork::Child) => {
1106 // Each child exits with its index
1107 exit(i);
1108 }
1109 Err(_) => panic!("Fork {} failed", i),
1110 }
1111 }
1112 }
1113
1114 #[test]
1115 fn test_getpgrp_in_parent() {
1116 // Test getpgrp in parent process
1117 let parent_pgrp = getpgrp();
1118 assert!(parent_pgrp > 0);
1119 }
1120
1121 #[test]
1122 fn test_close_retry_ok_and_ebadf() {
1123 // Create a pipe to obtain valid fds
1124 let mut fds = [0; 2];
1125 assert_eq!(unsafe { libc::pipe(&raw mut fds[0]) }, 0);
1126
1127 // Close write end via close_retry (should succeed)
1128 close_retry(fds[1]).expect("close_retry should close valid fd");
1129
1130 // Wrap read end in File to close it once; drop immediately
1131 let read_fd = fds[0];
1132 unsafe { std::fs::File::from_raw_fd(read_fd) };
1133
1134 // Second close should be treated as success (EBADF path)
1135 close_retry(read_fd).expect("EBADF should be treated as success");
1136 }
1137 }