diff --git a/examples/example_daemon.rs b/examples/example_daemon.rs new file mode 100644 index 0000000..23e0558 --- /dev/null +++ b/examples/example_daemon.rs @@ -0,0 +1,21 @@ +/// run with `cargo run --example example_daemon` +use fork::{daemon, Fork}; +use std::process::Command; + +fn main() { + // Keep file descriptors open to print the pid of the daemon + match daemon(false, true) { + Ok(Fork::Child) => { + Command::new("sleep") + .arg("300") + .output() + .expect("failed to execute process"); + } + Ok(Fork::Parent(pid)) => { + println!("daemon pid: {}", pid); + } + Err(_) => { + println!("Fork failed"); + } + } +} diff --git a/examples/example_touch_pid.rs b/examples/example_touch_pid.rs new file mode 100644 index 0000000..af588f1 --- /dev/null +++ b/examples/example_touch_pid.rs @@ -0,0 +1,27 @@ +/// run with `cargo run --example example_touch_pid` +use fork::{daemon, Fork}; +use std::fs::OpenOptions; +use std::process::Command; + +fn main() { + match daemon(false, false) { + Ok(Fork::Child) => { + Command::new("sleep") + .arg("300") + .output() + .expect("failed to execute process"); + } + Ok(Fork::Parent(pid)) => { + // touch file with name like pid + let file_name = format!("/tmp/{}.pid", pid); + OpenOptions::new() + .write(true) + .create(true) + .open(file_name) + .expect("failed to open file"); + } + Err(_) => { + println!("Fork failed"); + } + } +}