本文介绍了在 Rust 中写入子进程的标准输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
?
推荐答案
您可以创建一个标准输入管道并在其上写入字节.
You can create a stdin pipe and write the bytes on it.
- 由于
Command::output
会立即关闭标准输入,因此您必须使用Command::spawn
. Command::spawn
默认继承标准输入.你必须使用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!
")?;
// Close stdin to finish and avoid indefinite blocking
drop(child_stdin);
let output = child.wait_with_output()?;
println!("output = {:?}", output);
Ok(())
}
这篇关于在 Rust 中写入子进程的标准输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!