Constantine
Constantine

Reputation: 2032

Redirect output of child process spawned from Rust

I need to redirect output of a spawned child process. This is what I tried but it doesn't work:

Command::new(cmd)
    .args(&["--testnet",
            "--fast",
            format!("&>> {}", log_path).as_str()])
    .stdin(Stdio::piped())
    .stdout(Stdio::inherit())
    .spawn()

Upvotes: 6

Views: 5028

Answers (3)

ManWithA 1000Dev
ManWithA 1000Dev

Reputation: 71

They have added a new (in 7/6/2017 https://github.com/rust-lang/rust/pull/42133) std::process::Stdio::from function that also accepts files and works on both windows and unix systems. example:

use std::fs::File;
use std::process::Command;

fn main() {
    let f = File::create("path/to/some/log.log").unwrap();
    let mut cmd = Command::new("some command")
        .stdout(std::process::Stdio::from(f))
        .spawn()
        .unwrap();
    cmd.wait().unwrap();
}

Upvotes: 7

Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 88556

You can't redirect output with > when starting another program like that. Operators like >, >>, | and similar ones are interpreted by your shell and are not a native functionality of starting programs. Since the Command API doesn't emulate a shell, this won't work. So instead of passing it in args you have to use other methods of the process API to achieve what you want.

Short lived program

If the program to start is usually finished immediately, you might just want to wait until it's done and collect its output then. Then you can simply use the Command::output():

use std::process::Command;
use std::fs::File;
use std::io::Write;

let output = Command::new("rustc")
    .args(&["-V", "--verbose"])
    .output()?;

let mut f = File::create("rustc.log")?;
f.write_all(&output.stdout)?;

(Playground)

Note: the code above has to be in a function that returns a Result in order for the ? operator to work (it just passes errors up).

Long lived program

But maybe your program is not short lived and you don't want to wait until it's finished before doing anything with the output. In that case you should capture stdout and call Command::spawn(). Then you can access the ChildStdout which implements Read:

use std::process::{Command, Stdio};
use std::fs::File;
use std::io;

let child = Command::new("ping")
    .args(&["-c", "10", "google.com"])
    .stdout(Stdio::piped())
    .spawn()?;

let mut f = File::create("ping.log")?;
io::copy(&mut child.stdout.unwrap(), &mut f)?;

(Playground)

That way, ping.log is written on the fly every time the command outputs new data.

Upvotes: 10

the8472
the8472

Reputation: 43042

To directly use a file as output without intermediate copying from a pipe, you have to pass the file descriptor. The code is platform-specific, but with conditional compilation you can make it work on Windows too.

let f = File::create("foo.log").unwrap();
let fd = f.as_raw_fd();
// from_raw_fd is only considered unsafe if the file is used for mmap
let out = unsafe {Stdio::from_raw_fd(fd)};
let child = Command::new("foo")
    .stdout(out)
    .spawn().unwrap();

Upvotes: 6

Related Questions