File: example_touch_pid.rs

package info (click to toggle)
rust-fork 0.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 376 kB
  • sloc: makefile: 2
file content (31 lines) | stat: -rw-r--r-- 998 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#![allow(clippy::expect_used)]
#![allow(clippy::match_wild_err_arm)]

/// run with `cargo run --example example_touch_pid`
use std::{fs::OpenOptions, process::Command};

use fork::{Fork, daemon};

fn main() {
    match daemon(false, false) {
        Ok(Fork::Child) => {
            // Touch a PID file from the daemon process itself
            let file_name = format!("/tmp/{}.pid", std::process::id());
            OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&file_name)
                .expect("failed to open file");

            // Do some work
            Command::new("sleep")
                .arg("300")
                .output()
                .expect("failed to execute process");
        }
        // Parent exits inside daemon(); this arm is unreachable.
        Ok(Fork::Parent(_)) => unreachable!("daemon exits parent processes"),
        Err(err) => eprintln!("daemon failed: {err}"),
    }
}