-
-
Save mmstick/e94d8b92cdc99c7d9c6ffed788574059 to your computer and use it in GitHub Desktop.
Child Processes Aren't Closing?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::{BufRead, BufReader}; | |
use std::process::{Child, Command, Stdio}; | |
fn main() { | |
for id in 1..64_000 { | |
let child = Command::new("echo").arg(id.to_string()) | |
.stdout(Stdio::piped()).stderr(Stdio::piped()) | |
.spawn().unwrap(); | |
output(child, false); | |
} | |
} | |
fn output(child: Child, quiet: bool) { | |
let stderr = child.stderr.expect("unable to open stderr of child"); | |
let mut stderr_buffer = BufReader::new(stderr).lines(); | |
if quiet { | |
for stderr in stderr_buffer { | |
if let Ok(stderr) = stderr { | |
println!("{}", stderr); | |
} else { | |
break | |
} | |
} | |
} else { | |
let stdout = child.stdout.expect("unable to open stdout of child"); | |
let mut stdout_buffer = BufReader::new(stdout).lines(); | |
// Attempt to read from stdout and stderr simultaneously until both are exhausted of messages. | |
loop { | |
if let Some(stdout) = stdout_buffer.next() { | |
// If a message is received from standard output, it will be sent as a `Pipe::Stdout`. | |
if let Ok(stdout) = stdout { | |
println!("{}", stdout); | |
} else { | |
break | |
} | |
} else if let Some(stderr) = stderr_buffer.next() { | |
if let Ok(stderr) = stderr { | |
println!("{}", stderr); | |
} else { | |
break | |
} | |
} else { | |
break | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment