Debian Codegraph @

examples/example_pipe.rs

raw symbols SCIP
1 #![allow(clippy::expect_used)]
2 #![allow(clippy::unwrap_used)]
3 #![allow(clippy::panic)]
4 #![allow(clippy::uninlined_format_args)]
5 #![allow(clippy::match_wild_err_arm)]
6
7 /// run with `cargo run --example example_pipe`
8 use std::{
9 io::prelude::*,
10 process::{Command, Stdio, exit},
11 };
12
13 use fork::{Fork, fork, setsid};
14 use os_pipe::pipe;
15
16 fn main() {
17 // Create a pipe for communication
18 let (mut reader, writer) = pipe().expect("Failed to create pipe");
19
20 match fork() {
21 Ok(Fork::Child) => match fork() {
22 Ok(Fork::Child) => {
23 setsid().expect("Failed to setsid");
24 match Command::new("sleep")
25 .arg("300")
26 .stdin(Stdio::null())
27 .stdout(Stdio::null())
28 .stderr(Stdio::null())
29 .spawn()
30 {
31 Ok(child) => {
32 println!("Child pid: {}", child.id());
33
34 // Write child pid to the pipe
35 let mut writer = writer; // Shadowing to prevent move errors
36 writeln!(writer, "{}", child.id()).expect("Failed to write to pipe");
37
38 exit(0);
39 }
40 Err(e) => {
41 eprintln!("Error running command: {:?}", e);
42 exit(1);
43 }
44 }
45 }
46 Ok(Fork::Parent(_)) => exit(0),
47 Err(e) => {
48 eprintln!("Error spawning process: {:?}", e);
49 exit(1)
50 }
51 },
52 Ok(Fork::Parent(_)) => {
53 drop(writer);
54
55 // Read the child pid from the pipe
56 let mut child_pid_str = String::new();
57 reader
58 .read_to_string(&mut child_pid_str)
59 .expect("Failed to read from pipe");
60
61 if let Ok(child_pid) = child_pid_str.trim().parse::<i32>() {
62 println!("Received child pid: {}", child_pid);
63 } else {
64 eprintln!("Failed to parse child pid");
65 }
66 }
67 Err(e) => eprintln!("Error spawning process: {:?}", e),
68 }
69 }