What is the correct way to redirect stdio when spawning a process in Rust?

I see two ways to do this (Rust v0.9). For the examples below, suppose I want to redirect STDOUT to some file.

The first would be to get a file descriptor for the file, and then pass it to the structure std::run::ProcessOptions. Here's how to do it std::run::process_status:

let mut opt_prog = Process::new(prog, args, ProcessOptions {
    env: None,
    dir: None,
    in_fd:  Some(unsafe { libc::dup(libc::STDIN_FILENO)  }),
    out_fd: Some(unsafe { libc::dup(libc::STDOUT_FILENO) }),
    err_fd: Some(unsafe { libc::dup(libc::STDERR_FILENO) })
});

It receives the usual filedescriptors for STDIN, STDOUT and STDERR and installs them. But how do I get a file descriptor for some arbitrary file that I opened in Rust? I did not find a way to do this.


The second option is to simply use ProcessOptions by default through ProcessOptions::new(), which opens the channel for stdin, stdout and stderr and allows you to capture them, for example:

let pgm = "ls";
let args = ~[~"-lh"];

match Process::new(pgm, args, ProcessOptions::new()) {
    None => println("fubar"),
    Some(mut p) => {
        {
            let process = &mut p;
            let rdr = process.output();  // grab STDOUT output
            let out = rdr.read_to_str();
            // write output to your file of choice here
        }
        p.close_input();
        p.close_outputs();
        p.finish();
    }
}

, , - .

, , , STDOUT, ? process.error() STDERR, . - STDIN, .

?

+3
1

std::os::unix::AsRawFd, std::io::fs::File as_raw_fd .

Unix- std::os::unix::prelude. , , , , , :

#![feature(globs)]

use std::io::fs::File;
use std::os::unix::prelude::*;

fn main() {
    let p = Path::new("/etc/passwd");
    let f = File::open(&p).unwrap();
    let fd = f.as_raw_fd();
    println!("{} fd: {}", p.as_str().unwrap(), fd);
}
+2

All Articles