process-wrap
- API documentation.
- Dual-licensed with Apache 2.0 and MIT.
- Successor to command-group.
- Minimum Supported Rust Version: 1.88.0.
- Only the latest stable rustc version is supported.
- We try to conservatively bump the MSRV,
- but MSRV increases will not incur major version bumps.
Unlike command-group, process-wrap doesn't implement a single cross-platform API.
Instead, it provides composable wrappers which implement a single concern each.
It is left to the developer to use the appropriate wrapper(s) for their use-case and platform.
As the successor to (and containing a lot of the code of) command-group, versioning starts at 6.0.0.
You can think of it as a breaking change to command-group, though the paradigm is quite different.
The full test suite from command-group was retained: process-wrap has parity on functionality as a starting point.
Quick start
[dependencies]
process-wrap = { version = "11.0.0", features = ["tokio1"] }
By default, the crate does nothing, you need to enable either the std or Tokio "frontend". A default
set of wrappers are enabled; you may choose to only compile those you need, see the features list.
use process_wrap::tokio::*;
let mut child = CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(ProcessGroup::leader())
.spawn()?;
let status = child.wait().await?;
dbg!(status);
or on Windows
use process_wrap::tokio::*;
let mut child = CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(JobObject)
.spawn()?;
let status = child.wait().await?;
dbg!(status);
or with sessions
use process_wrap::tokio::*;
let mut child = CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(ProcessSession)
.spawn()?;
let status = child.wait().await?;
dbg!(status);
or with multiple wrappers
use process_wrap::tokio::*;
let mut child = CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(ProcessSession)
.wrap(KillOnDrop)
.spawn()?;
let status = child.wait().await?;
dbg!(status);
or with std
[dependencies]
process-wrap = { version = "11.0.0", features = ["std"] }
use process_wrap::std::*;
let mut child = CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(ProcessGroup::leader())
.spawn()?;
let status = child.wait()?;
dbg!(status);
Wrappers
Job object
- Platforms: Windows
- Like command-group.
- Feature:
job-object (default)
CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(JobObject)
.spawn()?;
CreationFlags and JobObject may be registered in either order. JobObject preserves every
requested flag, temporarily adds CREATE_SUSPENDED while assigning the process, and resumes it
after assignment unless the caller explicitly requested CREATE_SUSPENDED.
To terminate the job without the child, for example from another thread while the child is being
waited on, get a JobObjectHandle from the JobObjectChild. It can be cloned and sent across
threads, and keeps the job open for as long as it's held, even after the child is dropped:
let mut child = CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(JobObject)
.spawn()?;
let job = (child.as_ref() as &dyn std::any::Any)
.downcast_ref::<JobObjectChild>()
.expect("JobObject is the outermost wrapper")
.job_handle();
std::thread::spawn(move || job.terminate(1));
let status = child.wait().await?;
Process group
- Platforms: POSIX (Linux, Mac, BSDs...)
- Like command-group >=5.0.0.
- Feature:
process-group (default)
CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(ProcessGroup::leader())
.spawn()?;
Or join a different group instead:
CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(ProcessGroup::attach_to(pgid))
.spawn()?;
For Windows process groups, use CreationFlags::NEW_PROCESS_GROUP and/or JobObject.
Process session
- Platforms: POSIX (Linux, Mac, BSDs...)
- Like command-group <5.0.0.
- Feature:
process-session (default)
This combines creating a new session and a new group, and setting this process as leader.
To join the session from another process, use ProcessGroup::attach_to() instead.
CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(ProcessSession)
.spawn()?;
Reset signal mask
- Platforms: POSIX (Linux, Mac, BSDs...)
- Feature:
reset-sigmask
This resets the signal mask of the process instead of inheriting it from the parent.
CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(ResetSigmask)
.spawn()?;
Creation flags
- Platforms: Windows
- Like command-group.
- Feature:
creation-flags (default)
This is a shim to allow setting Windows process creation flags with this API, as otherwise they'd be overwritten.
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
let child = CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(CreationFlags(CREATE_NO_WINDOW.0))
.wrap(JobObject)
.spawn()?;
CreationFlags and JobObject may be registered in either order. JobObject preserves every
requested flag, temporarily adds CREATE_SUSPENDED while assigning the process, and resumes it
after assignment unless the caller explicitly requested CREATE_SUSPENDED.
Kill on drop
- Platforms: all
- Like command-group.
- Feature:
kill-on-drop (default)
This is a shim to allow wrappers to handle the kill-on-drop flag, as it can't be read from Command.
let child = CommandWrap::with_new("watch", |command| { command.arg("ls"); })
.wrap(KillOnDrop)
.wrap(ProcessGroup::leader())
.spawn()?;
drop(child);
Propagate Thread Death
- Platforms: Linux only
- Feature:
propagate-thread-death
This sets parent-death signal on the child process.
use std::{io, thread, process::{Stdio, Command}};
// PropagateThreadDeath ties the subprocess lifetime to the spawning thread.
let handle = thread::spawn(|| {
let child = CommandWrap::from(Command::new("yes"))
.wrap(PropagateThreadDeath::default())
.spawn()?;
Ok::<_, io::Error>(child.id())
});
let dead_pid = handle
.join()
.expect("Thread panicked")
.expect("Thread failed to spawn");
// The `yes` subprocess was killed by the kernel.
The signal is sent when the thread that spawned the child exits, or the whole process does.
With Tokio, that's whichever runtime thread calls spawn(): a worker thread of a
multi-thread runtime exits when the runtime shuts down, but the thread calling block_on keeps
running after it. See the Tokio wrapper's documentation for the other cases.
For control over which thread the child is tied to, use the std wrapper from a thread you manage;
both frontends can be enabled together.
Your own
Implementing a wrapper is done via a set of traits.
The std and Tokio sides are completely separate, due to the different underlying APIs.
Of course you can (and should) re-use/share code wherever possible if implementing both.
At minimum, you must implement CommandWrapper (from process_wrap::std and/or process_wrap::tokio).
These provide the same functionality, but differ in the exact types specified.
Here's the most basic impl (shown for Tokio):
#[derive(Debug)]
pub struct YourWrapper;
impl CommandWrapper for YourWrapper {}
That's right, all member methods are optional.
The trait provides extension or hook points into the lifecycle of a Command:
fn extend(&mut self, other: Self) is called if .wrap(YourWrapper) is done twice.
Only one wrapper of a given type can exist, so this gives the stored instance an opportunity to
incorporate all or part of the second, concretely typed wrapper. By default, this does nothing
(that is, only the first registered wrapper instance of a type applies).
fn pre_spawn(&mut self, command: &mut Command, core: &CommandWrap) is called before the
command is spawned, and gives mutable access to it. It also gives mutable access to the wrapper
instance, so state can be stored if needed. The core reference gives access to data from other
wrappers; for example, that's how CreationFlags on Windows works along with JobObject. Noop by
default.
fn post_spawn(&mut self, command: &mut Command, child: &mut tokio::process::Child, core: &CommandWrap)
is called after spawn, and should be used for any necessary cleanups. It is offered for completeness
but is expected to be less used than wrap_child(). Noop by default.
fn wrap_child(&mut self, child: Box<dyn ChildWrapper>, core: &CommandWrap) is
called after all post_spawn()s have run. If your wrapper needs to override the methods on Child,
then it should create an instance of its own type implementing ChildWrapper and return it
here. Child wraps are in order: you may end up with a Foo(Bar(Child)) or a Bar(Foo(Child))
depending on if .wrap(Foo).wrap(Bar) or .wrap(Bar).wrap(Foo) was called. If your functionality
is order-dependent, make sure to specify so in your documentation! Default is noop: no wrapping is
performed and the input child is returned as-is.
Refer to the API documentation for more detail and the specifics of child wrapper traits.
Features
Frontends
std: enables the std-based API.
tokio1: enables the Tokio-based API.
Both can exist at the same time, but generally you should use one or the other.
Wrappers