【发布时间】:2017-03-10 19:15:12
【问题描述】:
我正在用 Rust 编写的 shell 中实现 I/O 重定向。通过使用带有原始文件描述符的不安全代码和来自 libc crate 的 pipe(),我成功地在两个子进程之间进行管道传输。
当我尝试将最后一个子进程的stdout 重定向到我有权访问的文件时,它失败了:
extern crate libc;
use std::process::{Command, Stdio};
use std::os::unix::io::{FromRawFd, IntoRawFd};
use std::fs::File;
use self::libc::c_int;
fn main() {
let mut fds = [-1 as c_int, -1 as c_int];
let fd1 = File::open("test1").unwrap().into_raw_fd();
let fd2 = File::open("test2").unwrap().into_raw_fd();
let fd3 = File::open("test3").unwrap().into_raw_fd();
println!("{:?}, {:?}, {:?}", fd1, fd2, fd3);
unsafe {
libc::pipe(&mut fds[0] as *mut c_int);
let cmd1 = Command::new("ls")
.arg("/")
.stdout(Stdio::from_raw_fd(fds[1]))
.spawn()
.unwrap();
let mut cmd2 = Command::new("grep")
.arg("etc")
.stdin(Stdio::from_raw_fd(fds[0]))
.stdout(Stdio::from_raw_fd(fd1))
.spawn()
.unwrap();
let _result = cmd2.wait().unwrap();
}
}
上一段的结果:
3, 4, 5
grep: write error: Bad file descriptor
似乎文件描述符没有正确返回,但如果没有名为 test1、test2 和 test3 的文件,File::open(_).unwrap() 应该恐慌而不是假装打开了文件。
如果移除对文件的重定向,即只使用管道,则代码可以正常工作。
【问题讨论】:
标签: rust file-descriptor libc