Skip to main content

RunningProcess

Struct RunningProcess 

Source
pub struct RunningProcess { /* private fields */ }
Expand description

A handle to a process spawned by a runner.

Implementations§

Source§

impl RunningProcess

Source

pub async fn wait_for_line( &mut self, predicate: impl Fn(&str) -> bool, within: Duration, ) -> Result<String>

Wait until a stdout line matches predicate (returning that line), or fail with Error::NotReady when within elapses — or immediately when stdout closes before a match (e.g. the child exited and no descendant kept the pipe open), since no further line can arrive. A child that exits while a descendant still holds its stdout keeps the stream open, so that case waits out the deadline — the pipe, not the process, is what this probe watches.

The readiness idiom: start a server, wait for its “listening on …” banner, then use it — no arbitrary sleeps.

§Caveats
  • Consumes stdout up to and including the matching line (the same one-shot stdout drain stdout_lines uses — if stdout was already consumed by an earlier stdout_lines / output_events / wait_for_line, or was not piped, this returns an Err rather than a stream that is forever NotReady). Continue with finish for the outcome and stderr; the other probes don’t touch stdout.
  • A failed probe does not kill the child, and — unlike stdout_lines — it does not arm the Command::timeout watchdog: this probe is bounded only by its own within, and the command’s timeout is enforced later by the consuming verb (finish). So a probe can never tear the tree down or flip the run’s outcome to TimedOut, matching wait_for / wait_for_port.
Source

pub async fn wait_for<F, Fut>( &mut self, check: F, within: Duration, ) -> Result<()>
where F: FnMut() -> Fut, Fut: Future<Output = bool>,

Wait until check (re-invoked every ~50 ms, first attempt immediate) returns true, or fail with Error::NotReady when within elapses — or immediately when the child exits first (a dead process never becomes ready).

The check is any async predicate — an HTTP health endpoint, a file appearing, a database accepting connections. Doesn’t touch the child’s pipes, so it composes with any later consumption (wait, output_string, …). A failed probe does not kill the child. The deadline bounds the polling loop, not an in-flight check: a slow check future can overrun within by its own duration.

Source

pub async fn wait_for_port( &mut self, addr: SocketAddr, within: Duration, ) -> Result<()>

Wait until a TCP connection to addr is accepted, or fail with Error::NotReady when within elapses — or immediately when the child exits first.

One connect attempt per ~50 ms tick (each attempt itself bounded so a stalled connect can’t overrun the deadline); the probe connection is dropped as soon as it succeeds. Doesn’t touch the child’s pipes; a failed probe does not kill the child.

Source§

impl RunningProcess

Source

pub fn stdout_lines(&mut self) -> Result<StdoutLines>

Stream the child’s standard output line by line. Call this once.

Standard error is drained in the background and discarded — use output_string when you need both. The command’s timeout bounds the stream: at the deadline the process tree is killed, pipes close, and a following finish reports Outcome::TimedOut even if the child caught the signal and exited cleanly within the grace.

Returns Err instead of a silently-empty stream when stdout was not piped or a streaming verb was already called on this handle.

Source

pub async fn finish(self) -> Result<Finished>

Finish a streamed run: wait for exit and return a Finished carrying the Outcome and the stderr collected in the background by stdout_lines.

A run killed by its timeout reports Outcome::TimedOut, even if the child caught the signal and exited cleanly within the grace — matching the bulk verbs.

Designed to pair with stdout_lines (consume the stdout stream first), but safe to call on its own — any pipe the stream didn’t take is drained here so the child can never block on a full pipe.

Source

pub fn output_events(&mut self) -> Result<OutputEvents>

Stream both stdout and stderr as a single ordered sequence of OutputEvent items. Call this once.

Interleaving is best-effort; the two streams are polled fairly so a continuously-ready stream can’t starve the other. Returns Err instead of a silently-empty stream when stdout was not piped or was already consumed. Call finish after draining — its stderr will be empty since stderr was delivered as events.

Source§

impl RunningProcess

Source

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

The OS process id, or None if the child has already been reaped.

Source

pub fn start_time(&self) -> SystemTime

Wall-clock instant the process was started.

Source

pub fn elapsed(&self) -> Duration

Time elapsed since the process started (sampled now).

Source

pub fn cpu_time(&self) -> Option<Duration>

Available on crate feature stats only.

CPU time (user + kernel) consumed so far, if the platform can report it.

Source

pub fn peak_memory_bytes(&self) -> Option<u64>

Available on crate feature stats only.

Peak resident memory in bytes, if the platform can report it.

Source

pub fn stdout_line_count(&self) -> usize

Lines read from stdout so far (counts every line, even ones dropped by an OutputBufferPolicy). Live only once stdout is being pumped.

Source

pub fn stderr_line_count(&self) -> usize

Lines read from stderr so far (see stdout_line_count).

Source

pub fn take_stdin(&mut self) -> Option<ProcessStdin>

Take the interactive stdin writer, if the command was built with keep_stdin_open. Returns None after the first call (or when stdin was not kept open).

Source

pub fn kills_tree_on_drop(&self) -> bool

Whether dropping this handle will tear down (hard-kill) the process tree.

true — owns a private process group; drop hard-kills the whole tree. false — runs inside a shared ProcessGroup whose lifetime the group owns (drop does not kill the tree), or a scripted test double (no OS tree).

Source

pub async fn output_string(self) -> Result<ProcessResult<String>>

Drain both streams, wait for exit, and return the captured text output (line-normalized to \n).

If you previously called stdout_lines and consumed some lines from the stream, those already-consumed lines are gone from the buffer; output_string returns only the unconsumed tail. To capture the full output, avoid mixing streaming and output_string.

Source

pub async fn output_bytes(self) -> Result<ProcessResult<Vec<u8>>>

Drain both streams, wait for exit, and return the exact raw stdout bytes (stderr captured as text). On timeout/cancellation returns bytes read so far — a killed run’s bytes are a best-effort prefix.

§Errors

Returns Error::Io(InvalidInput) if stdout is not piped, or if a prior streaming call already consumed stdout as decoded lines (the raw bytes cannot be reconstructed).

Source

pub async fn wait(self) -> Result<Outcome>

Wait for exit, returning how the run ended as an Outcome (output is drained and discarded so the child never blocks on a full pipe).

Reports the raw outcome — timeout and signals are not raised as errors here. Exception: cancellation via Command::cancel_on always errors with Error::Cancelled.

Source

pub async fn shutdown(self, grace: Duration) -> Result<Outcome>

Gracefully stop the process tree: SIGTERM, wait up to grace, then SIGKILL any survivor. On Windows the kill is atomic and grace is not awaited.

Only an own-group handle can be shut down here — a shared-group handle returns Error::Unsupported because shutting it down would tear down the caller’s other children too.

If the configured timeout deadline already elapsed when shutdown is called the run is classified as Outcome::TimedOut.

Source

pub async fn profile(self, every: Duration) -> Result<RunProfile>

Available on crate feature stats only.

Run the process to completion while sampling CPU and memory every every, returning a RunProfile. Behaves like wait — output is discarded, timeout applies. A zero every is clamped to 1 ms.

Source

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

Send a kill to the process without waiting for it to exit. The owning group still governs the rest of the tree.

The Outcome afterwards is platform-dependent: Signalled on Unix, Exited with a platform code on Windows. A scripted handle reports Signalled(None).

Idempotent: killing an already-reaped child is a successful no-op.

Trait Implementations§

Source§

impl Debug for RunningProcess

Source§

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

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

impl Drop for RunningProcess

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

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> Any for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Source§

fn type_name(&self) -> &'static str

Source§

impl<T> AnySync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more