Library for creating a new process detached from the controling terminal (daemon) using the fork and setsid syscalls.
Rust
86
83 commits
updated Jul 18, 2026
Library for creating a new process detached from the controlling terminal (daemon) on Unix-like systems.
fork and setsid syscalls, new methods
can be created to achieve the same goalAdd fork to your Cargo.toml:
[dependencies]
fork = "0.10.0"
Or use cargo-add:
cargo add fork
use fork::{daemon, Fork};
use std::process::Command;
fn main() {
if let Ok(Fork::Child) = daemon(false, false) {
// This code runs in the daemon process
Command::new("sleep")
.arg("300")
.output()
.expect("failed to execute process");
}
}
use fork::{fork, Fork, waitpid, WIFEXITED, WEXITSTATUS};
match fork() {
Ok(Fork::Parent(child)) => {
println!("Parent process, child PID: {}", child);
// Wait for child and check exit status
match waitpid(child) {
Ok(status) => {
if WIFEXITED(status) {
println!("Child exited with code: {}", WEXITSTATUS(status));
}
}
Err(e) => eprintln!("waitpid failed: {}", e),
}
}
Ok(Fork::Child) => {
println!("Child process");
std::process::exit(0);
}
Err(e) => eprintln!("Fork failed: {}", e),
}
use fork::{fork, Fork};
match fork() {
Ok(Fork::Parent(child)) => {
println!("Spawned child with PID: {}", child);
}
Ok(Fork::Child) => {
println!("I'm the child!");
std::process::exit(0);
}
Err(err) => {
eprintln!("Fork failed: {}", err);
// Access the underlying errno if needed
if let Some(code) = err.raw_os_error() {
eprintln!("OS error code: {}", code);
}
}
}
Supervisors should prefer the additive typed API. ProcessId and
ProcessGroupId accept only positive values, Signal cannot represent signal
zero, and process versus process-group delivery are separate operations.
use fork::{ChildEvent, wait_any_event_nohang};
while let Some(event) = wait_any_event_nohang()? {
match event {
ChildEvent::Exited { pid, code } => println!("{pid} exited with {code}"),
ChildEvent::Signalled { pid, signal } => {
println!("{pid} terminated by signal {signal}");
}
ChildEvent::Stopped { pid, signal } => {
println!("{pid} stopped by signal {signal}");
}
ChildEvent::Continued { pid } => println!("{pid} continued"),
}
}
# Ok::<(), std::io::Error>(())
The group helpers are explicit:
create_current_process_group() creates a group in the child after fork.create_process_group(process) performs the matching parent-side operation
to close the fork/exec race.join_process_group(process, group) joins another owned child.signal_process(process, signal) targets exactly one PID.signal_process_group(group, signal) targets every group member without
exposing the raw negative-PID kill(2) convention.wait_event* and wait_any_event* report typed exit, signal, stop, and
continue events and retry waitpid(2) after EINTR.On Linux and FreeBSD, a supervisor that is not PID 1 can opt into the OS subreaper role before starting its workload:
use fork::{acquire_subreaper, wait_any_event};
acquire_subreaper()?;
// Start the supervised workload. If an intermediate parent exits, its
// orphaned descendants are adopted here and become visible to wait_any_*.
let event = wait_any_event()?;
println!("observed child event: {event:?}");
# Ok::<(), std::io::Error>(())
Acquisition is process-wide, is not inherited across fork, and is preserved
across exec. Adopted processes may have PIDs the supervisor did not spawn
directly, so unknown PIDs from wait_any_* are expected. Subreaping does not
enumerate live descendants or signal processes that escape an owned process
group. The API returns ErrorKind::Unsupported outside Linux and FreeBSD.
A supervisor normally stops a service by sending a signal and waiting for it.
That works only while the process responsible for cleanup is alive. If a
process broker is killed with SIGKILL, crashes, or is terminated by the
out-of-memory killer, it cannot run a destructor or an async cleanup task. The
service may therefore continue running without its owner.
Waiting for another process to notice a closed IPC connection is not
equivalent: the broker can die before publishing the new process-group ID, and
a numeric ID may be reused before delayed cleanup reaches it.
ProcessGroupGuard makes the cleanup authority exist before the workload
starts and keeps it beside—not inside—the workload group.
Tokio supervisor
│ broker IPC
▼
single-threaded broker ─── owner socket ─── guard helper
│ │
│ spawns into reserved group │ unexpected EOF
▼ │ sends SIGKILL
process group ◄───────────────────────────────┘
└── workload process(es)
The broker owns the socket endpoint and the ProcessGroupGuard value. The
helper owns the other endpoint and deliberately remains outside the workload
group. The kernel closes the broker endpoint even after SIGKILL; the helper
observes EOF and kills the complete group. During a clean shutdown, disarm
sends an explicit record instead, so the helper exits without signaling the
workload.
use std::time::Duration;
use fork::{PreparedCommand, ProcessGroup, ProcessGroupGuard, wait_event};
let timeout = Duration::from_secs(3);
let mut guard = ProcessGroupGuard::new()?;
let mut command = PreparedCommand::new("/bin/sleep")?;
command
.arg("5")?
.process_group(ProcessGroup::Join(guard.process_group()));
let child = command.spawn(timeout)?;
// The workload has joined, so the temporary group anchor can retire.
guard.activate(timeout)?;
let event = wait_event(child.process())?;
// Normal completion: reap the helper without signaling the now-empty group.
guard.disarm(timeout)?;
println!("workload finished: {event:?}");
# Ok::<(), Box<dyn std::error::Error>>(())
The repository includes this lifecycle as the runnable
process_group_guard example.
Internally, new first creates a short-lived anchor which reserves a valid
process-group ID, then creates the out-of-group guard. The caller starts the
workload in that reserved group and calls activate, which retires and reaps
the anchor. One guard helper and one close-on-exec socket remain for the active
group. Dropping an armed guard is fail-closed: it closes the endpoint, lets the
helper kill the group, and performs bounded helper cleanup.
Arc.guard_process exists so an all-child wait loop can classify an
unexpected helper event; such an event means containment has failed and the
broker must kill the affected group.activate removes the anchor, leaving one
sleeping helper process and one socket endpoint per active group. The helper
blocks in read and consumes no scheduled CPU while healthy, but one process
per group is still a real capacity cost for high-cardinality supervisors.close_range; the portable fallback scans up to the soft descriptor limit.
Parent cleanup briefly yields, then uses bounded exponential sleeps capped at
five milliseconds rather than busy polling.activate and disarm use caller-supplied nonzero cleanup deadlines. The
fail-closed Drop fallback can block for up to three seconds while reaping a
defective helper.setsid or joins another group has escaped. Use an
operating-system-specific facility such as a FreeBSD process reaper or Linux
cgroup when stronger containment is required.pipe_cloexec() and socket_pair_cloexec() return owned endpoints and prevent
them from leaking through a successful exec. A pipe is suitable for a
one-way startup-status handshake; a socket pair supports bidirectional framed
messages between a supervisor and its dedicated process broker.
On Linux and the supported BSDs, close-on-exec is set atomically when each
endpoint is created. macOS requires a fcntl fallback, so construct broker IPC
before starting threads that could concurrently execute another program.
PreparedCommand is an additive API for a dedicated, single-threaded process
broker. It snapshots the environment and materializes the executable path,
arguments, working directory, pointer arrays, process-group intent, descriptor
mappings, descriptor close bounds, and numeric credentials before fork. The
child then performs only reviewed system calls before execve or _exit.
use std::time::Duration;
use fork::{PreparedCommand, ProcessGroup};
let mut command = PreparedCommand::new("/bin/sleep")?;
command.arg("5")?.process_group(ProcessGroup::New);
let child = command.spawn(Duration::from_secs(3))?;
println!("started {}", child.process());
# Ok::<(), Box<dyn std::error::Error>>(())
The executable is direct: the library performs neither shell parsing nor
PATH lookup. Descriptor sources are owned and duplicated above all targets
before fork, so overlapping mappings cannot destroy another mapping's source.
Descriptors can be mapped, inherited at their existing number, or explicitly
closed; everything else above standard error is closed before exec. Optional
identity transitions apply pre-resolved supplementary groups, primary GID, and
UID in that order—the library never performs account-database lookup after
fork. By default the child also clears its signal mask and restores portable
catchable dispositions so ignored or blocked supervisor signals do not leak
through exec. ChildSignalState::Inherit is an explicit opt-out.
An internal close-on-exec pipe distinguishes successful execve from a typed
pre-exec failure. The original low-level API remains unchanged.
checked_daemon() is the additive alternative when the invoking process must
remain alive and learn whether daemon initialization really succeeded. Call it
before creating threads. The intermediate child creates a session and performs
the second fork; the detached grandchild initializes resources and then uses
its DaemonNotifier to report ready or explicitly fail and exit.
The detached daemon receives the same default signal-state reset before
initialization; callers may explicitly request inheritance when necessary.
use std::time::Duration;
use fork::{CheckedDaemon, DaemonOptions, checked_daemon};
let mut options = DaemonOptions::new();
options
.current_directory("/")?
.redirect_standard_io_to_null()?;
match checked_daemon(options, Duration::from_secs(3))? {
CheckedDaemon::Parent(process) => {
println!("daemon {} is ready", process.process());
}
CheckedDaemon::Daemon(notifier) => {
// Bind sockets, acquire locks, create PID files, and initialize logs.
notifier.notify_ready()?;
// Start the daemon event loop here.
}
}
# Ok::<(), Box<dyn std::error::Error>>(())
The deadline covers partial records and repeated EINTR, not only the first
pipe byte. Timeout and failure paths send KILL, reap the intermediate child,
and return any process or group that could not be confirmed clean through
DaemonError::cleanup_pending(). The existing daemon() behavior and
signature are unchanged.
fork_process() - Forks with a checked ProcessId in the parentfork() - Creates a new child processdaemon(nochdir, noclose) - Creates a daemon using double-fork pattern
nochdir: if false, changes working directory to /noclose: if false, redirects stdin/stdout/stderr to /dev/nullsetsid() - Creates a new session and sets the process group IDwaitpid(pid) - Waits for child process to change state (blocking; returns raw status; retries on signals)waitpid_nohang(pid) - Checks child status without blocking (returns Option<status>; for supervisors/polling)wait_any() - Waits for any child process and returns (pid, status)wait_any_nohang() - Checks any child without blocking and returns Option<(pid, status)>getpgrp() - Returns the process group IDgetpid() - Returns the current process IDgetppid() - Returns the parent process IDchdir() - Changes current directory to /redirect_stdio() - Redirects stdin/stdout/stderr to /dev/null (recommended)close_fd() - Closes stdin, stdout, and stderr (legacy, use redirect_stdio() instead)pipe_cloexec() - Creates an owned close-on-exec unidirectional pipesocket_pair_cloexec() - Creates an owned close-on-exec Unix socket pairPreparedCommand - Materializes and directly executes a broker commandchecked_daemon() - Performs checked, bounded double-fork detachmentWIFEXITED(status) - Check if child exited normallyWEXITSTATUS(status) - Get exit code (if exited normally)WIFSIGNALED(status) - Check if child was terminated by signalWTERMSIG(status) - Get terminating signal (if signaled)See the documentation for detailed usage.
When using daemon(false, false), it will change directory to / and redirect stdin/stdout/stderr to /dev/null.
This matters for daemon startup code. Use absolute paths for PID files, logs,
sockets, and config files: after chdir("/"), File::create("myapp.pid")
tries to create /myapp.pid, not a file in the launch directory. With
noclose = false, any println!, eprintln!, or panic output from that
failure goes to /dev/null, which can make it look like the daemon block never
ran. Use daemon(true, false) if relative paths should stay relative to the
launch directory, and use noclose = true or a readiness pipe while debugging
startup failures.
Test running:
$ cargo run
Use ps to check the process:
$ ps -axo ppid,pid,pgid,sess,tty,tpgid,stat,uid,%mem,%cpu,command | egrep "myapp|sleep|PID"
Output:
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
Key points:
PPID == 1 - Parent is init/systemd (orphaned process)TTY = ?? - No controlling terminalPGID = 48737 - Own process groupProcess hierarchy:
1 - root (init/systemd)
└── 48738 myapp PGID - 48737
└── 48753 sleep PGID - 48737
The daemon() function implements the classic double-fork pattern:
This prevents the daemon from ever acquiring a controlling terminal.
daemon() intentionally follows the classic daemon pattern: after the first
fork succeeds, the original parent exits before later setup steps run. If the
launcher must remain alive and observe setup success or failure, use
checked_daemon() with an explicit timeout and DaemonNotifier. It preserves
the existing daemon() contract while providing checked detachment without
requiring each caller to implement its own wire protocol and cleanup path.
See examples/checked_daemon_pattern.rs for a complete checked-startup example.
daemon() uses _exit in the forked parents to avoid running non-async-signal-safe destructors between fork/exec (POSIX-safe on Linux/macOS/BSD).redirect_stdio() retries open() and dup2() on EINTR; close_fd() calls close() once and treats EINTR as success to avoid closing a reused fd.redirect_stdio() over close_fd() so file descriptors 0,1,2 stay occupied (avoids accidental log/data corruption).ProcessId as a checked live handle and remove it
immediately after a terminal ChildEvent. Use your own monotonic identity for
durable restart/history state because operating systems reuse PIDs.Run tests:
cargo test --all-targets --all-features -- --test-threads=1
The CI lifecycle suite runs natively on Linux, macOS, and FreeBSD.
See tests/README.md for detailed information about integration tests.
This library is designed for Unix-like operating systems:
See the examples/ directory for more usage examples:
example_daemon.rs - Daemon creationchecked_daemon_pattern.rs - Bounded checked startup with explicit readinessexample_pipe.rs - Fork with pipe communicationexample_touch_pid.rs - PID file creationRun an example:
cargo run --example example_daemon
Contributions are welcome! Please ensure:
cargo testcargo fmtcargo clippy -- -D warningsBSD 3-Clause License - see LICENSE file for details.
Overall
Maintained
Code review
crates.io
Latest release
Releases this year
457 followers · starred Feb 2024
56 followers · starred Mar 2024
Library for creating a new process detached from the controling terminal (daemon) using the fork and setsid syscalls.
Rust
86
83 commits
updated Jul 18, 2026
Library for creating a new process detached from the controlling terminal (daemon) on Unix-like systems.
fork and setsid syscalls, new methods
can be created to achieve the same goalAdd fork to your Cargo.toml:
[dependencies]
fork = "0.10.0"
Or use cargo-add:
cargo add fork
use fork::{daemon, Fork};
use std::process::Command;
fn main() {
if let Ok(Fork::Child) = daemon(false, false) {
// This code runs in the daemon process
Command::new("sleep")
.arg("300")
.output()
.expect("failed to execute process");
}
}
use fork::{fork, Fork, waitpid, WIFEXITED, WEXITSTATUS};
match fork() {
Ok(Fork::Parent(child)) => {
println!("Parent process, child PID: {}", child);
// Wait for child and check exit status
match waitpid(child) {
Ok(status) => {
if WIFEXITED(status) {
println!("Child exited with code: {}", WEXITSTATUS(status));
}
}
Err(e) => eprintln!("waitpid failed: {}", e),
}
}
Ok(Fork::Child) => {
println!("Child process");
std::process::exit(0);
}
Err(e) => eprintln!("Fork failed: {}", e),
}
use fork::{fork, Fork};
match fork() {
Ok(Fork::Parent(child)) => {
println!("Spawned child with PID: {}", child);
}
Ok(Fork::Child) => {
println!("I'm the child!");
std::process::exit(0);
}
Err(err) => {
eprintln!("Fork failed: {}", err);
// Access the underlying errno if needed
if let Some(code) = err.raw_os_error() {
eprintln!("OS error code: {}", code);
}
}
}
Supervisors should prefer the additive typed API. ProcessId and
ProcessGroupId accept only positive values, Signal cannot represent signal
zero, and process versus process-group delivery are separate operations.
use fork::{ChildEvent, wait_any_event_nohang};
while let Some(event) = wait_any_event_nohang()? {
match event {
ChildEvent::Exited { pid, code } => println!("{pid} exited with {code}"),
ChildEvent::Signalled { pid, signal } => {
println!("{pid} terminated by signal {signal}");
}
ChildEvent::Stopped { pid, signal } => {
println!("{pid} stopped by signal {signal}");
}
ChildEvent::Continued { pid } => println!("{pid} continued"),
}
}
# Ok::<(), std::io::Error>(())
The group helpers are explicit:
create_current_process_group() creates a group in the child after fork.create_process_group(process) performs the matching parent-side operation
to close the fork/exec race.join_process_group(process, group) joins another owned child.signal_process(process, signal) targets exactly one PID.signal_process_group(group, signal) targets every group member without
exposing the raw negative-PID kill(2) convention.wait_event* and wait_any_event* report typed exit, signal, stop, and
continue events and retry waitpid(2) after EINTR.On Linux and FreeBSD, a supervisor that is not PID 1 can opt into the OS subreaper role before starting its workload:
use fork::{acquire_subreaper, wait_any_event};
acquire_subreaper()?;
// Start the supervised workload. If an intermediate parent exits, its
// orphaned descendants are adopted here and become visible to wait_any_*.
let event = wait_any_event()?;
println!("observed child event: {event:?}");
# Ok::<(), std::io::Error>(())
Acquisition is process-wide, is not inherited across fork, and is preserved
across exec. Adopted processes may have PIDs the supervisor did not spawn
directly, so unknown PIDs from wait_any_* are expected. Subreaping does not
enumerate live descendants or signal processes that escape an owned process
group. The API returns ErrorKind::Unsupported outside Linux and FreeBSD.
A supervisor normally stops a service by sending a signal and waiting for it.
That works only while the process responsible for cleanup is alive. If a
process broker is killed with SIGKILL, crashes, or is terminated by the
out-of-memory killer, it cannot run a destructor or an async cleanup task. The
service may therefore continue running without its owner.
Waiting for another process to notice a closed IPC connection is not
equivalent: the broker can die before publishing the new process-group ID, and
a numeric ID may be reused before delayed cleanup reaches it.
ProcessGroupGuard makes the cleanup authority exist before the workload
starts and keeps it beside—not inside—the workload group.
Tokio supervisor
│ broker IPC
▼
single-threaded broker ─── owner socket ─── guard helper
│ │
│ spawns into reserved group │ unexpected EOF
▼ │ sends SIGKILL
process group ◄───────────────────────────────┘
└── workload process(es)
The broker owns the socket endpoint and the ProcessGroupGuard value. The
helper owns the other endpoint and deliberately remains outside the workload
group. The kernel closes the broker endpoint even after SIGKILL; the helper
observes EOF and kills the complete group. During a clean shutdown, disarm
sends an explicit record instead, so the helper exits without signaling the
workload.
use std::time::Duration;
use fork::{PreparedCommand, ProcessGroup, ProcessGroupGuard, wait_event};
let timeout = Duration::from_secs(3);
let mut guard = ProcessGroupGuard::new()?;
let mut command = PreparedCommand::new("/bin/sleep")?;
command
.arg("5")?
.process_group(ProcessGroup::Join(guard.process_group()));
let child = command.spawn(timeout)?;
// The workload has joined, so the temporary group anchor can retire.
guard.activate(timeout)?;
let event = wait_event(child.process())?;
// Normal completion: reap the helper without signaling the now-empty group.
guard.disarm(timeout)?;
println!("workload finished: {event:?}");
# Ok::<(), Box<dyn std::error::Error>>(())
The repository includes this lifecycle as the runnable
process_group_guard example.
Internally, new first creates a short-lived anchor which reserves a valid
process-group ID, then creates the out-of-group guard. The caller starts the
workload in that reserved group and calls activate, which retires and reaps
the anchor. One guard helper and one close-on-exec socket remain for the active
group. Dropping an armed guard is fail-closed: it closes the endpoint, lets the
helper kill the group, and performs bounded helper cleanup.
Arc.guard_process exists so an all-child wait loop can classify an
unexpected helper event; such an event means containment has failed and the
broker must kill the affected group.activate removes the anchor, leaving one
sleeping helper process and one socket endpoint per active group. The helper
blocks in read and consumes no scheduled CPU while healthy, but one process
per group is still a real capacity cost for high-cardinality supervisors.close_range; the portable fallback scans up to the soft descriptor limit.
Parent cleanup briefly yields, then uses bounded exponential sleeps capped at
five milliseconds rather than busy polling.activate and disarm use caller-supplied nonzero cleanup deadlines. The
fail-closed Drop fallback can block for up to three seconds while reaping a
defective helper.setsid or joins another group has escaped. Use an
operating-system-specific facility such as a FreeBSD process reaper or Linux
cgroup when stronger containment is required.pipe_cloexec() and socket_pair_cloexec() return owned endpoints and prevent
them from leaking through a successful exec. A pipe is suitable for a
one-way startup-status handshake; a socket pair supports bidirectional framed
messages between a supervisor and its dedicated process broker.
On Linux and the supported BSDs, close-on-exec is set atomically when each
endpoint is created. macOS requires a fcntl fallback, so construct broker IPC
before starting threads that could concurrently execute another program.
PreparedCommand is an additive API for a dedicated, single-threaded process
broker. It snapshots the environment and materializes the executable path,
arguments, working directory, pointer arrays, process-group intent, descriptor
mappings, descriptor close bounds, and numeric credentials before fork. The
child then performs only reviewed system calls before execve or _exit.
use std::time::Duration;
use fork::{PreparedCommand, ProcessGroup};
let mut command = PreparedCommand::new("/bin/sleep")?;
command.arg("5")?.process_group(ProcessGroup::New);
let child = command.spawn(Duration::from_secs(3))?;
println!("started {}", child.process());
# Ok::<(), Box<dyn std::error::Error>>(())
The executable is direct: the library performs neither shell parsing nor
PATH lookup. Descriptor sources are owned and duplicated above all targets
before fork, so overlapping mappings cannot destroy another mapping's source.
Descriptors can be mapped, inherited at their existing number, or explicitly
closed; everything else above standard error is closed before exec. Optional
identity transitions apply pre-resolved supplementary groups, primary GID, and
UID in that order—the library never performs account-database lookup after
fork. By default the child also clears its signal mask and restores portable
catchable dispositions so ignored or blocked supervisor signals do not leak
through exec. ChildSignalState::Inherit is an explicit opt-out.
An internal close-on-exec pipe distinguishes successful execve from a typed
pre-exec failure. The original low-level API remains unchanged.
checked_daemon() is the additive alternative when the invoking process must
remain alive and learn whether daemon initialization really succeeded. Call it
before creating threads. The intermediate child creates a session and performs
the second fork; the detached grandchild initializes resources and then uses
its DaemonNotifier to report ready or explicitly fail and exit.
The detached daemon receives the same default signal-state reset before
initialization; callers may explicitly request inheritance when necessary.
use std::time::Duration;
use fork::{CheckedDaemon, DaemonOptions, checked_daemon};
let mut options = DaemonOptions::new();
options
.current_directory("/")?
.redirect_standard_io_to_null()?;
match checked_daemon(options, Duration::from_secs(3))? {
CheckedDaemon::Parent(process) => {
println!("daemon {} is ready", process.process());
}
CheckedDaemon::Daemon(notifier) => {
// Bind sockets, acquire locks, create PID files, and initialize logs.
notifier.notify_ready()?;
// Start the daemon event loop here.
}
}
# Ok::<(), Box<dyn std::error::Error>>(())
The deadline covers partial records and repeated EINTR, not only the first
pipe byte. Timeout and failure paths send KILL, reap the intermediate child,
and return any process or group that could not be confirmed clean through
DaemonError::cleanup_pending(). The existing daemon() behavior and
signature are unchanged.
fork_process() - Forks with a checked ProcessId in the parentfork() - Creates a new child processdaemon(nochdir, noclose) - Creates a daemon using double-fork pattern
nochdir: if false, changes working directory to /noclose: if false, redirects stdin/stdout/stderr to /dev/nullsetsid() - Creates a new session and sets the process group IDwaitpid(pid) - Waits for child process to change state (blocking; returns raw status; retries on signals)waitpid_nohang(pid) - Checks child status without blocking (returns Option<status>; for supervisors/polling)wait_any() - Waits for any child process and returns (pid, status)wait_any_nohang() - Checks any child without blocking and returns Option<(pid, status)>getpgrp() - Returns the process group IDgetpid() - Returns the current process IDgetppid() - Returns the parent process IDchdir() - Changes current directory to /redirect_stdio() - Redirects stdin/stdout/stderr to /dev/null (recommended)close_fd() - Closes stdin, stdout, and stderr (legacy, use redirect_stdio() instead)pipe_cloexec() - Creates an owned close-on-exec unidirectional pipesocket_pair_cloexec() - Creates an owned close-on-exec Unix socket pairPreparedCommand - Materializes and directly executes a broker commandchecked_daemon() - Performs checked, bounded double-fork detachmentWIFEXITED(status) - Check if child exited normallyWEXITSTATUS(status) - Get exit code (if exited normally)WIFSIGNALED(status) - Check if child was terminated by signalWTERMSIG(status) - Get terminating signal (if signaled)See the documentation for detailed usage.
When using daemon(false, false), it will change directory to / and redirect stdin/stdout/stderr to /dev/null.
This matters for daemon startup code. Use absolute paths for PID files, logs,
sockets, and config files: after chdir("/"), File::create("myapp.pid")
tries to create /myapp.pid, not a file in the launch directory. With
noclose = false, any println!, eprintln!, or panic output from that
failure goes to /dev/null, which can make it look like the daemon block never
ran. Use daemon(true, false) if relative paths should stay relative to the
launch directory, and use noclose = true or a readiness pipe while debugging
startup failures.
Test running:
$ cargo run
Use ps to check the process:
$ ps -axo ppid,pid,pgid,sess,tty,tpgid,stat,uid,%mem,%cpu,command | egrep "myapp|sleep|PID"
Output:
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
Key points:
PPID == 1 - Parent is init/systemd (orphaned process)TTY = ?? - No controlling terminalPGID = 48737 - Own process groupProcess hierarchy:
1 - root (init/systemd)
└── 48738 myapp PGID - 48737
└── 48753 sleep PGID - 48737
The daemon() function implements the classic double-fork pattern:
This prevents the daemon from ever acquiring a controlling terminal.
daemon() intentionally follows the classic daemon pattern: after the first
fork succeeds, the original parent exits before later setup steps run. If the
launcher must remain alive and observe setup success or failure, use
checked_daemon() with an explicit timeout and DaemonNotifier. It preserves
the existing daemon() contract while providing checked detachment without
requiring each caller to implement its own wire protocol and cleanup path.
See examples/checked_daemon_pattern.rs for a complete checked-startup example.
daemon() uses _exit in the forked parents to avoid running non-async-signal-safe destructors between fork/exec (POSIX-safe on Linux/macOS/BSD).redirect_stdio() retries open() and dup2() on EINTR; close_fd() calls close() once and treats EINTR as success to avoid closing a reused fd.redirect_stdio() over close_fd() so file descriptors 0,1,2 stay occupied (avoids accidental log/data corruption).ProcessId as a checked live handle and remove it
immediately after a terminal ChildEvent. Use your own monotonic identity for
durable restart/history state because operating systems reuse PIDs.Run tests:
cargo test --all-targets --all-features -- --test-threads=1
The CI lifecycle suite runs natively on Linux, macOS, and FreeBSD.
See tests/README.md for detailed information about integration tests.
This library is designed for Unix-like operating systems:
See the examples/ directory for more usage examples:
example_daemon.rs - Daemon creationchecked_daemon_pattern.rs - Bounded checked startup with explicit readinessexample_pipe.rs - Fork with pipe communicationexample_touch_pid.rs - PID file creationRun an example:
cargo run --example example_daemon
Contributions are welcome! Please ensure:
cargo testcargo fmtcargo clippy -- -D warningsBSD 3-Clause License - see LICENSE file for details.
Overall
Maintained
Code review
crates.io
Latest release
Releases this year
457 followers · starred Feb 2024
56 followers · starred Mar 2024