From b3229f8e5ec1b7d79e43f69f45ee8a56cbc432bd Mon Sep 17 00:00:00 2001 From: nbari Date: Sun, 21 Jul 2024 18:40:21 +0200 Subject: [PATCH] daemon examples --- examples/example_daemon.rs | 21 +++++++++++++++++++++ examples/example_touch_pid.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 examples/example_daemon.rs create mode 100644 examples/example_touch_pid.rs 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"); + } + } +}