Popen

Struct Popen 

Source
pub struct Popen {
    pub stdin: Option<File>,
    pub stdout: Option<File>,
    pub stderr: Option<File>,
    /* private fields */
}
Expand description

Interface to a running subprocess.

Popen is the parent’s interface to a created subprocess. The child process is started in the constructor, so owning a Popen value indicates that the specified program has been successfully launched. To prevent accumulation of zombie processes, the child is waited upon when a Popen goes out of scope, which can be prevented using the detach method.

Depending on how the subprocess was configured, its input, output, and error streams can be connected to the parent and available as stdin, stdout, and stderr public fields. If you need to read the output and errors into memory (or provide input as a memory slice), use the communicate family of methods.

Popen instances can be obtained with the create method, or using the popen method of the Exec type. Subprocesses can be connected into pipes, most easily achieved using using Exec.

Fields§

§stdin: Option<File>

If stdin was specified as Redirection::Pipe, this will contain a writable File connected to the standard input of the child process.

§stdout: Option<File>

If stdout was specified as Redirection::Pipe, this will contain a readable File connected to the standard output of the child process.

§stderr: Option<File>

If stderr was specified as Redirection::Pipe, this will contain a readable File connected to the standard error of the child process.

Implementations§

Source§

impl Popen

Source

pub fn create(argv: &[impl AsRef<OsStr>], config: PopenConfig) -> Result<Popen>

Execute an external program in a new process.

argv is a slice containing the program followed by its arguments, such as &["ps", "x"]. config specifies details how to create and interface to the process.

For example, this launches the cargo update command:

Popen::create(&["cargo", "update"], PopenConfig::default())?;
§Errors

If the external program cannot be executed for any reason, an error is returned. The most typical reason for execution to fail is that the program is missing on the PATH, but other errors are also possible. Note that this is distinct from the program running and then exiting with a failure code - this can be detected by calling the wait method to obtain its exit status.

Source

pub fn detach(&mut self)

Mark the process as detached.

This method has no effect on the OS level, it simply tells Popen not to wait for the subprocess to finish when going out of scope. If the child process has already finished, or if it is guaranteed to finish before Popen goes out of scope, calling detach has no effect.

Source

pub fn pid(&self) -> Option<u32>

Return the PID of the subprocess, if it is known to be still running.

Note that this method won’t actually check whether the child process is still running, it will only return the information last set using one of create, wait, wait_timeout, or poll. For a newly created Popen, pid() always returns Some.

Source

pub fn exit_status(&self) -> Option<ExitStatus>

Return the exit status of the subprocess, if it is known to have finished.

Note that this method won’t actually check whether the child process has finished, it only returns the previously available information. To check or wait for the process to finish, call wait, wait_timeout, or poll.

Source

pub fn communicate_start(&mut self, input_data: Option<Vec<u8>>) -> Communicator

Prepare to send input to the subprocess and capture its output.

Sets up writing input_data to the subprocess’s stdin (then closing it) while simultaneously reading stdout and stderr until end-of-file. The actual I/O is deferred until you call read or read_string on the returned Communicator.

The simultaneous reading and writing avoids deadlock when the subprocess produces output before consuming all input. (A naive write-then-read approach would hang because the parent blocks on writing while the child blocks on having its output read.)

Unlike communicate_bytes, the Communicator allows timeout, size limits, and access to partial output on error.

Source

pub fn communicate_bytes( &mut self, input_data: Option<&[u8]>, ) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)>

Send input to the subprocess and capture its output.

Writes input_data to the subprocess’s stdin and closes it, while simultaneously reading stdout and stderr until end-of-file. Returns the captured output as a pair of Option<Vec<u8>>, where None indicates a stream not redirected to Pipe.

The simultaneous reading and writing avoids deadlock when the subprocess produces output before consuming all input.

This method does not wait for the subprocess to exit, only for its output streams to reach EOF. In rare cases where a process continues after closing its streams, Popen::drop will wait for it. Use wait, detach, or terminate if you need explicit control.

For timeout and size limit support, use communicate_start instead.

§Panics

If input_data is provided and stdin was not redirected to a pipe. Also, if input_data is not provided and stdin was redirected to a pipe.

§Errors
  • Err(::std::io::Error) if a system call fails
Source

pub fn communicate( &mut self, input_data: Option<&str>, ) -> Result<(Option<String>, Option<String>)>

Feed the subprocess with data and capture its output as string.

This is a convenience method equivalent to communicate_bytes, but with input as &str and output as String. Invalid UTF-8 sequences, if found, are replaced with the U+FFFD Unicode replacement character.

§Panics

The same as with communicate_bytes.

§Errors
  • Err(::std::io::Error) if a system call fails
Source

pub fn poll(&mut self) -> Option<ExitStatus>

Check whether the process is still running, without blocking or errors.

This checks whether the process is still running and if it is still running, None is returned, otherwise Some(exit_status). This method is guaranteed not to block and is exactly equivalent to wait_timeout(Duration::from_secs(0)).unwrap_or(None).

Source

pub fn wait(&mut self) -> Result<ExitStatus>

Wait for the process to finish, and return its exit status.

If the process has already finished, it will exit immediately, returning the exit status. Calling wait after that will return the cached exit status without executing any system calls.

§Errors

Returns an Err if a system call fails in an unpredicted way. This should not happen in normal usage.

Source

pub fn wait_timeout(&mut self, dur: Duration) -> Result<Option<ExitStatus>>

Wait for the process to finish, timing out after the specified duration.

This function behaves like wait(), except that the caller will be blocked for roughly no longer than dur. It returns Ok(None) if the timeout is known to have elapsed.

On Unix-like systems, timeout is implemented by calling waitpid(..., WNOHANG) in a loop with adaptive sleep intervals between iterations.

Source

pub fn terminate(&mut self) -> Result<()>

Terminate the subprocess.

On Unix-like systems, this sends the SIGTERM signal to the child process, which can be caught by the child in order to perform cleanup before exiting. On Windows, it is equivalent to kill().

Source

pub fn kill(&mut self) -> Result<()>

Kill the subprocess.

On Unix-like systems, this sends the SIGKILL signal to the child process, which cannot be caught.

On Windows, it invokes TerminateProcess on the process handle with equivalent semantics.

Trait Implementations§

Source§

impl Debug for Popen

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Popen

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl PopenExt for Popen

Source§

fn send_signal(&self, signal: i32) -> Result<()>

Send the specified signal to the child process. Read more
Source§

fn send_signal_group(&self, signal: i32) -> Result<()>

Send the specified signal to the child’s process group. Read more

Auto Trait Implementations§

§

impl Freeze for Popen

§

impl RefUnwindSafe for Popen

§

impl Send for Popen

§

impl Sync for Popen

§

impl Unpin for Popen

§

impl UnwindSafe for Popen

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.