Redirect output of child process spawned from Rust
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.
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();