shell – 如何通过Rust中的stdin将输入发送到程序
发布时间:2020-12-15 21:43:37 所属栏目:安全 来源:网络整理
导读:我试图在Rust写一个 shell. shell的一个功能是能够将输入重定向到文件,将文件重定向到输入,以及将程序的输出管道输出到另一个程序.我在std中使用run :: process_output函数来运行程序并获取它们的输出,但我不知道如何在运行之后将输入发送为程序员的stdin.有
我试图在Rust写一个
shell.
shell的一个功能是能够将输入重定向到文件,将文件重定向到输入,以及将程序的输出管道输出到另一个程序.我在std中使用run :: process_output函数来运行程序并获取它们的输出,但我不知道如何在运行之后将输入发送为程序员的stdin.有没有办法创建一个直接连接到run程序的对象,并像在stdin中输入一样输入输入?
解决方法
该程序演示了如何启动外部程序并传输其标准输出 – > stdin在一起:
use std::io::{BufRead,BufReader,BufWriter,Write}; use std::process::{Command,Stdio}; fn main() { // Create some argument vectors for lanuching external programs let a = vec!["view","-h","file.bam"]; let outsam = vec!["view","-bh","-o","rust.bam","-"]; let mut child = Command::new("samtools") .args(&a) .stdout(Stdio::piped()) .spawn() .unwrap(); let outchild = Command::new("samtools") .args(&outsam) .stdin(Stdio::piped()) .spawn() .unwrap(); // Create a handle and writer for the stdin of the second process let mut outstdin = outchild.stdin.unwrap(); let mut writer = BufWriter::new(&mut outstdin); // Loop over the output from the first process if let Some(ref mut stdout) = child.stdout { for line in BufReader::new(stdout).lines() { let mut l: String = line.unwrap(); // Need to add an end of line character back to the string let eol: &str = "n"; l = l + eol; // Print some select lines from the first child to stdin of second if (l.chars().skip(0).next().unwrap()) == '@' { // convert the string into bytes and write to second process let bytestring = l.as_bytes(); writer.write_all(bytestring).unwrap(); } } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |