File: example_pipe.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 (69 lines) | stat: -rw-r--r-- 2,209 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
#![allow(clippy::uninlined_format_args)]
#![allow(clippy::match_wild_err_arm)]

/// run with `cargo run --example example_pipe`
use std::{
    io::prelude::*,
    process::{Command, Stdio, exit},
};

use fork::{Fork, fork, setsid};
use os_pipe::pipe;

fn main() {
    // Create a pipe for communication
    let (mut reader, writer) = pipe().expect("Failed to create pipe");

    match fork() {
        Ok(Fork::Child) => match fork() {
            Ok(Fork::Child) => {
                setsid().expect("Failed to setsid");
                match Command::new("sleep")
                    .arg("300")
                    .stdin(Stdio::null())
                    .stdout(Stdio::null())
                    .stderr(Stdio::null())
                    .spawn()
                {
                    Ok(child) => {
                        println!("Child pid: {}", child.id());

                        // Write child pid to the pipe
                        let mut writer = writer; // Shadowing to prevent move errors
                        writeln!(writer, "{}", child.id()).expect("Failed to write to pipe");

                        exit(0);
                    }
                    Err(e) => {
                        eprintln!("Error running command: {:?}", e);
                        exit(1);
                    }
                }
            }
            Ok(Fork::Parent(_)) => exit(0),
            Err(e) => {
                eprintln!("Error spawning process: {:?}", e);
                exit(1)
            }
        },
        Ok(Fork::Parent(_)) => {
            drop(writer);

            // Read the child pid from the pipe
            let mut child_pid_str = String::new();
            reader
                .read_to_string(&mut child_pid_str)
                .expect("Failed to read from pipe");

            if let Ok(child_pid) = child_pid_str.trim().parse::<i32>() {
                println!("Received child pid: {}", child_pid);
            } else {
                eprintln!("Failed to parse child pid");
            }
        }
        Err(e) => eprintln!("Error spawning process: {:?}", e),
    }
}