在Rust中写入子进程的stdin吗? [英] Write to child process' stdin in Rust?
本文介绍了在Rust中写入子进程的stdin吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Rust的 std :: process :: Command
允许通过 stdin
方法,但该方法似乎只接受现有文件或管道.
Rust's std::process::Command
allows configuring the process' stdin via the stdin
method, but it appears that that method only accepts existing files or pipes.
给出一片字节,如何将其写入 Command
的标准输入?
Given a slice of bytes, how would you go about writing it to the stdin of a Command
?
推荐答案
您可以创建一个stdin管道并在其上写入字节.
You can create a stdin pipe and write the bytes on it.
- 当
Command :: output
立即关闭标准输入时,您必须使用Command :: spawn
. -
Command :: spawn
默认情况下继承stdin.您必须使用Command :: stdin
更改行为.
- As
Command::output
immediately closes the stdin, you'll have to useCommand::spawn
. Command::spawn
inherits stdin by default. You'll have to useCommand::stdin
to change the behavior.
以下是示例(操场):
use std::io::{self, Write};
use std::process::{Command, Stdio};
fn main() -> io::Result<()> {
let mut child = Command::new("cat")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
let child_stdin = child.stdin.as_mut().unwrap();
child_stdin.write_all(b"Hello, world!\n")?;
// Close stdin to finish and avoid indefinite blocking
drop(child_stdin);
let output = child.wait_with_output()?;
println!("output = {:?}", output);
Ok(())
}
这篇关于在Rust中写入子进程的stdin吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文