Skip to content

Instantly share code, notes, and snippets.

@flaneur2020
Last active February 18, 2025 09:05
Show Gist options
  • Save flaneur2020/4e74d7c8acc6b8dbe41cacb28c131dba to your computer and use it in GitHub Desktop.
Save flaneur2020/4e74d7c8acc6b8dbe41cacb28c131dba to your computer and use it in GitHub Desktop.
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::main]
async fn main() {
let mut child = tokio::process::Command::new("cat")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.expect("Failed to spawn cat process");
child
.stdin
.as_mut()
.unwrap()
.write_all(b"Hello, world!")
.await
.unwrap();
// can not pass eof to childprocess, will hang
child.stdin.as_mut().unwrap().shutdown().await.unwrap();
// will not hang
// drop(child.stdin.take());
let mut buffer = Vec::new();
child
.stdout
.as_mut()
.unwrap()
.read_to_end(&mut buffer)
.await
.unwrap();
println!("{}", String::from_utf8_lossy(&buffer));
// Wait for the child to exit
let status = child.wait().await.expect("Failed to wait for cat process");
println!("Child process exited with status: {}", status);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment