Crate subprocess

source ·
Expand description

Execution of and interaction with external processes and pipelines.

The entry points to the crate are the Popen struct and the Exec builder. Popen is the interface to a running child process, modeled after Python’s subprocess.Popen, with modifications to make it fit to Rust. Exec provides a Rustic builder-style API with convenient methods for streaming and capturing of output, as well as combining Popen instances into pipelines.

Compared to std::process, the module follows the following additional features:

  • The communicate method for deadlock-free reading of subprocess output/error, while simultaneously providing it stdin.

  • Advanced redirection options, such as connecting standard streams to arbitary open files, or merging output streams like shell’s 2>&1 and 1>&2 operators.

  • Non-blocking and timeout methods to wait on the process: poll, wait, and wait_timeout.

  • Connecting multiple commands into OS-level pipelines.

Examples

Communicate with a process and optionally terminate it:

let mut p = Popen::create(&["ps", "x"], PopenConfig {
    stdout: Redirection::Pipe, ..Default::default()
})?;

// Obtain the output from the standard streams.
let (out, err) = p.communicate(None)?;

if let Some(exit_status) = p.poll() {
    // the process has finished
} else {
    // it is still running, terminate it
    p.terminate()?;
}

Use the Exec builder to execute a pipeline of commands and capture the output:

let dir_checksum = {
    Exec::shell("find . -type f") | Exec::cmd("sort") | Exec::cmd("sha1sum")
}.capture()?.stdout_str();

Modules

Subprocess extensions for Unix platforms.

Structs

A builder for Popen instances, providing control and convenience methods.
Marker value for stdin, stdout, and stderr methods of Exec and Pipeline.
A builder for multiple Popen instances connected via pipes.
Interface to a running subprocess.

Enums

Exit status of a process.
Error in Popen calls.
Instruction what to do with a stream in the child process.

Functions

Create a pipe.

Type Definitions

Result returned by calls in the subprocess crate in places where ::std::io::Result does not suffice.