Skip to content

Instantly share code, notes, and snippets.

@KumoKairo
Created May 5, 2020 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KumoKairo/1a6a950285feb3a5053a96d3869d7747 to your computer and use it in GitHub Desktop.
Save KumoKairo/1a6a950285feb3a5053a96d3869d7747 to your computer and use it in GitHub Desktop.
use std::process::{ Command, Stdio };
use std::io::{ Read, BufReader, Error, ErrorKind };
fn main() -> Result<(), Error> {
let external_process_name = "..."; // some process name that prints:
// line 1
// .. waits for 2 seconds ..
// line 2
// .. waits for 2 seconds ..
// line 3
println!("SPAWNING");
let mut child = Command::new(external_process_name)
.stdout(Stdio::piped())
.spawn()?;
println!("SPAWNED");
let stdout = child.stdout.take().ok_or_else(|| Error::new(ErrorKind::Other, "Coudln't capture stdout"))?;
let mut reader = BufReader::new(stdout);
let mut buf = Vec::with_capacity(100);
reader.read(&mut buf).expect("Can't read");
println!("Read 1 before .wait: {:?}", buf); // expecting it to wait for the first line and print 'line 1' in bytes
reader.read(&mut buf).expect("Can't read");
println!("Read 2 before .wait: {:?}", buf); // expecting it to wait for the second line and print 'line 2' in bytes
child.wait()?;
reader.read(&mut buf).expect("Can't read");
println!("Read after .wait {:?}", buf);
println!("DONE");
Ok(())
}
// Expected output:
// SPAWNING
// SPAWNED
// Read 1 before .wait: 'line 1' (in bytes for simplicity)
// Read 2 before .wait: 'line 2' (in bytes for simplicity)
// Read after .wait 'line 3' (in bytes for simplicity)
// DONE
// Received output:
// SPAWNING
// SPAWNED
// Read 1 before .wait: []
// Read 2 before .wait: []
// Read after .wait []
// DONE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment