Expand description
A library for passing arbitrary file descriptors when spawning child processes, and safely taking ownership of passed file descriptors within such a child process.
§Example
In the parent process:
use command_fds::{CommandFdExt, FdMapping};
use std::fs::File;
use std::io::stdin;
use std::os::fd::AsFd;
use std::os::unix::io::AsRawFd;
use std::process::Command;
// Open a file.
let file = File::open("Cargo.toml").unwrap();
// Prepare to run `ls -l /proc/self/fd` with some FDs mapped.
let mut command = Command::new("ls");
command.arg("-l").arg("/proc/self/fd");
command
.fd_mappings(vec![
// Map `file` as FD 3 in the child process.
FdMapping {
parent_fd: file.into(),
child_fd: 3,
},
// Map this process's stdin as FD 5 in the child process.
FdMapping {
parent_fd: stdin().as_fd().try_clone_to_owned().unwrap(),
child_fd: 5,
},
])
.unwrap();
// Spawn the child process.
let mut child = command.spawn().unwrap();
child.wait().unwrap();In the child process:
use command_fds::inherited::{init_inherited_fds, take_fd_ownership};
fn main() {
// SAFETY: This is called before anything else in the program.
unsafe {
init_inherited_fds();
}
// Get an OwnedFd for the file that was passed as FD 3 by the parent.
let inherited_file = take_fd_ownership(3).unwrap();
// Trying to take the same file descriptor again will return an error.
take_fd_ownership(3).expect_err("Can't take the same FD twice");
// Trying to take a file descriptor which wasn't passed will also return an error.
take_fd_ownership(4).expect_err("Can't take an FD which wasn't inherited");
}Modules§
- inherited
- Utilities for safely obtaining
OwnedFds for inherited file descriptors.
Structs§
- FdMapping
- A mapping from a file descriptor in the parent to a file descriptor in the child, to be applied when spawning a child process.
- FdMapping
Collision - Error setting up FD mappings, because there were two or more mappings for the same child FD.
Traits§
- Command
FdExt - Extension to add file descriptor mappings to a
Command.