Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect output of child process spawned from Rust

Tags:

io

process

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()
like image 519
Constantine Avatar asked May 13 '17 05:05

Constantine


2 Answers

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.

like image 171
Lukas Kalbertodt Avatar answered Oct 09 '22 14:10

Lukas Kalbertodt


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();
like image 42
the8472 Avatar answered Oct 09 '22 15:10

the8472