如何解决在Rust中重定向stdio管道和文件描述符
我的主要目的是在Rust中实现一个程序,以在本地管道上重定向stdio,与此类似
- 程序执行命令“ sh”并在父进程和子进程之间创建管道
- 子进程的输出通过管道(在本例中为提示符)到达父进程
- 我在终端上键入诸如“ pwd”之类的内容,这进入到子进程的管道中
- 子进程执行命令,然后通过管道将输出发送回父进程,并在我的终端上显示当前工作目录
最终,我的目标是让父进程充当代理,并通过远程ncat实例与子进程之间的TLS连接转发此I / O。现在,我正在尝试使管道部分正确。
我应该怎么做?我当前的代码段如下所示,但是我不确定重定向部分是否正确,因为我没有看到提示。
let message_string = String::from("fd_pipe\0");
let message = message_string.as_ptr() as *const c_void;
let mut command_output = std::process::Command::new("/bin/sh")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("cannot execute command");
let command_stdin = command_output.stdin.unwrap();
println!("command_stdin {}",command_stdin.as_raw_fd());
let command_stdout = command_output.stdout.unwrap();
println!("command_stdout {}",command_stdout.as_raw_fd());
let command_stderr = command_output.stderr.unwrap();
println!("command_stderr {}",command_stderr.as_raw_fd());
nix::unistd::dup2(tokio::io::stdin().as_raw_fd(),command_stdin.as_raw_fd());
nix::unistd::dup2(tokio::io::stdout().as_raw_fd(),command_stdout.as_raw_fd());
nix::unistd::dup2(tokio::io::stderr().as_raw_fd(),command_stderr.as_raw_fd());
编辑2020年11月2日
Rust论坛中的某个人已经为我提供了一个解决方案(https://users.rust-lang.org/t/redirect-stdio-pipes-and-file-descriptors/50751/8),我想我也会在这里分享它
let mut command_output = std::process::Command::new("/bin/sh")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("cannot execute command");
let mut command_stdin = command_output.stdin.unwrap();
println!("command_stdin {}",command_stdin.as_raw_fd());
let copy_stdin_thread = std::thread::spawn(move || {
io::copy(&mut io::stdin(),&mut command_stdin)
});
let mut command_stdout = command_output.stdout.unwrap();
println!("command_stdout {}",command_stdout.as_raw_fd());
let copy_stdout_thread = std::thread::spawn(move || {
io::copy(&mut command_stdout,&mut io::stdout())
});
let command_stderr = command_output.stderr.unwrap();
println!("command_stderr {}",command_stderr.as_raw_fd());
let copy_stderr_thread = std::thread::spawn(move || {
io::copy(&mut command_stderr,&mut io::stderr())
});
copy_stdin_thread.join().unwrap()?;
copy_stdout_thread.join().unwrap()?;
copy_stderr_thread.join().unwrap()?;
我的下一个问题是如何通过TLS连接将重定向的stdio链接到远程ncat侦听器?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。