use command_fds::{CommandFdExt, FdMapping};
use std::fs::{File, read_dir, read_link};
use std::io::stdin;
use std::os::fd::AsFd;
use std::os::unix::process::CommandExt;
use std::process::Command;
use std::thread::sleep;
use std::time::Duration;
fn list_fds() {
let dir = read_dir("/proc/self/fd").unwrap();
for entry in dir {
let entry = entry.unwrap();
let target = read_link(entry.path()).unwrap();
println!("{:?} -> {:?}", entry.file_name(), target);
}
}
fn main() {
list_fds();
let file = File::open("Cargo.toml").unwrap();
println!("File: {:?}", file);
list_fds();
let mut command = Command::new("ls");
command.arg("-l").arg("/proc/self/fd");
let stdin_fd = stdin().as_fd().try_clone_to_owned().unwrap();
command
.fd_mappings(vec![
FdMapping {
parent_fd: file.into(),
child_fd: 3,
},
FdMapping {
parent_fd: stdin_fd,
child_fd: 5,
},
])
.unwrap();
unsafe {
command.pre_exec(|| {
println!("pre_exec");
list_fds();
Ok(())
});
}
println!("Spawning command");
let mut child = command.spawn().unwrap();
sleep(Duration::from_millis(100));
println!("Spawned");
list_fds();
println!("Waiting for command");
println!("{:?}", child.wait().unwrap());
}