@std/os/process.ms#
Import each required symbol with import Name from "@std/os/process.ms".
CommandOutput Type#
Captured exit status and standard output/error from a completed command.
type CommandOutput {
exit_code Int
stdout Bytes
stderr Bytes
max_resident_bytes Int
}CommandOutput.exit_code#
The child’s exit status; 0 conventionally means success. A nonzero status is still an Ok result, and a child ended by a signal reports -1 on Unix.
exit_code IntCommandOutput.max_resident_bytes#
The child’s peak resident set size in bytes, or 0 when the host cannot report it.
max_resident_bytes IntCommandOutput.stderr#
Everything the child wrote to standard error, as raw bytes that may not be valid UTF-8.
stderr BytesCommandOutput.stdout#
Everything the child wrote to standard output, as raw bytes that may not be valid UTF-8.
stdout BytesCommands Interface#
The shape of run and spawn, for code that takes child-process operations as a
parameter so a test can pass a fake. Programs call the module functions run and
spawn directly.
interface Commands {
fn run(program String, arguments List[String], options RunOptions = RunOptions()) Result[CommandOutput, Error]
fn spawn(program String, arguments List[String], options SpawnOptions = SpawnOptions()) Result[Subprocess, Error]
}Commands.run#
Starts program directly, without a shell, searching the PATH, and waits for it to finish. arguments are passed after the program name, options.input is written to its standard input, and its output is captured.
Output beyond options.max_output_bytes in total across both streams returns EOVERFLOW, options.timeout returns ETIMEDOUT, and in both cases the child’s process group is killed. Cancelling the calling task also kills it.
options.cwd is the child’s working directory (null inherits the caller’s); options.env adds or replaces variables on top of the inherited environment, and a name that is empty or holds =, or a NUL byte anywhere, returns EINVAL. A cwd that does not exist returns ENOENT. Neither touches the caller’s own directory or environment, so concurrent tasks can run children in different directories.
fn run(program String, arguments List[String], options RunOptions = RunOptions()) Result[CommandOutput, Error]Commands.spawn#
Starts program directly, without a shell, searching the PATH, and returns a
live Subprocess that its scope closes. arguments follow the program name;
options.stdin, options.stdout, and options.stderr each choose a pipe (the
default), the parent’s own stream, or the null device. Returns EINVAL, ENOENT (no
such program or working directory), EACCES (not executable), or EIO when it
cannot start. Closing the Subprocess, or cancelling the acquiring execution,
kills the child’s process group.
options.cwd and options.env behave as in run.
fn spawn(program String, arguments List[String], options SpawnOptions = SpawnOptions()) Result[Subprocess, Error]CpuUsage Type#
Cumulative CPU time consumed by the current process, in integer microseconds.
type CpuUsage {
user_microseconds Int
system_microseconds Int
}CpuUsage.system_microseconds#
Kernel CPU time in microseconds.
system_microseconds IntCpuUsage.user_microseconds#
User CPU time in microseconds.
user_microseconds IntIdentityKind Enum#
Which of the process identities set_identity changes.
enum IdentityKind {
Uid
Gid
Euid
Egid
}IdentityKind.Egid#
The effective group id.
EgidIdentityKind.Euid#
The effective user id.
EuidIdentityKind.Gid#
The real group id.
GidIdentityKind.Uid#
The real user id.
UidProcessInfo Type#
Identity and invocation details for the current process.
type ProcessInfo {
pid Int
parent_pid Int
executable String
arguments List[String]
os String
architecture String
uid Int
gid Int
effective_uid Int
effective_gid Int
}ProcessInfo.architecture#
Processor architecture name, such as amd64 or arm64.
architecture StringProcessInfo.arguments#
The native argv including argv[0]. arguments() from @std/os/env.ms returns
the startup arguments without it.
arguments List[String]ProcessInfo.effective_gid#
Effective group id used for permission checks; -1 on Windows.
effective_gid IntProcessInfo.effective_uid#
Effective user id used for permission checks; -1 on Windows.
effective_uid IntProcessInfo.executable#
Absolute path of the running program file.
executable StringProcessInfo.gid#
Real group id; -1 on Windows, where ids are not numeric.
gid IntProcessInfo.os#
Operating system name, such as linux, darwin, or windows.
os StringProcessInfo.parent_pid#
Operating system id of the parent process at the time of the call.
parent_pid IntProcessInfo.pid#
Operating system id of this process.
pid IntProcessInfo.uid#
Real user id; -1 on Windows, where ids are not numeric.
uid IntResourceUsage Type#
Kernel resource counters for the current process. CPU times are integer microseconds; max_resident_bytes is bytes; other fields are counts, not durations or byte totals. Filesystem reads/writes count native block I/O on Unix and I/O operations on Windows. Unavailable Windows fault/context-switch counters are zero.
type ResourceUsage {
user_microseconds Int
system_microseconds Int
max_resident_bytes Int
minor_faults Int
major_faults Int
filesystem_reads Int
filesystem_writes Int
voluntary_switches Int
involuntary_switches Int
}ResourceUsage.filesystem_reads#
Block input operations charged to the process, as a count.
filesystem_reads IntResourceUsage.filesystem_writes#
Block output operations charged to the process, as a count.
filesystem_writes IntResourceUsage.involuntary_switches#
Context switches where the scheduler preempted the process, as a count.
involuntary_switches IntResourceUsage.major_faults#
Page faults that required disk I/O, as a count.
major_faults IntResourceUsage.max_resident_bytes#
Peak physical memory the process has held at once, in bytes.
max_resident_bytes IntResourceUsage.minor_faults#
Page faults served without disk I/O, as a count.
minor_faults IntResourceUsage.system_microseconds#
Cumulative CPU time the kernel spent on behalf of this process, in microseconds.
system_microseconds IntResourceUsage.user_microseconds#
Cumulative CPU time spent running this process’s own code, in microseconds.
user_microseconds IntResourceUsage.voluntary_switches#
Context switches where the process gave up the CPU, such as to wait for I/O, as a count.
voluntary_switches IntRunOptions Type#
Settings for run. Every field has a default, so RunOptions() runs the program
with no input, no output cap, no deadline, the caller’s directory and the inherited
environment.
type RunOptions {
input Bytes = "".to_bytes()
max_output_bytes Int? = null
timeout Duration? = null
cwd String? = null
env Map[String, String] = Map[String, String]()
}RunOptions.cwd#
The child’s working directory; null inherits the caller’s.
cwd String? = nullRunOptions.env#
Variables added to or replaced in the inherited environment.
env Map[String, String] = Map[String, String]()RunOptions.input#
Bytes written to the child’s standard input.
input Bytes = "".to_bytes()RunOptions.max_output_bytes#
Largest total output of both streams in bytes; null sets no cap. More returns EOVERFLOW.
max_output_bytes Int? = nullRunOptions.timeout#
How long the child may run; null waits without limit. Expiry returns ETIMEDOUT.
timeout Duration? = nullSignal Enum#
A signal to send to a process with kill or Subprocess.kill. The names are portable;
each maps to the host’s own signal number, which differs between systems.
Linux and macOS deliver the matching POSIX signal. Windows has no signals, so it uses the closest equivalent, or returns ENOTSUP where there is none:
| Signal | Linux and macOS | Windows |
|---|---|---|
Hangup | SIGHUP | ENOTSUP |
Interrupt | SIGINT | ends the process (Ctrl-Break cannot be aimed at one process, so there is no gentler form) |
Quit | SIGQUIT | ENOTSUP |
Terminate | SIGTERM | ends the process (TerminateProcess) |
Kill | SIGKILL | ends the process (TerminateProcess) |
Stop | SIGSTOP | suspends the process |
Continue | SIGCONT | resumes the process |
User1 | SIGUSR1 | ENOTSUP |
User2 | SIGUSR2 | ENOTSUP |
Subprocess.kill sends to the child’s whole process group (POSIX) or job object (Windows)
for the signals that end it. Windows suspends and resumes only the child itself.
enum Signal {
Hangup
Interrupt
Quit
Terminate
Kill
Stop
Continue
User1
User2
}Signal.Continue#
Resumes a process paused by Stop.
ContinueSignal.Hangup#
The controlling terminal closed; programs often reload their configuration.
HangupSignal.Interrupt#
The user’s interrupt request, as Ctrl-C sends.
InterruptSignal.Kill#
Ends the process at once; it cannot be handled or ignored.
KillSignal.Quit#
A request to quit, which may leave a core dump on Unix.
QuitSignal.Stop#
Pauses the process until Continue; it cannot be handled or ignored.
StopSignal.Terminate#
A polite request to end, which the process may handle or ignore.
TerminateSignal.User1#
The first signal whose meaning the receiving program defines.
User1Signal.User2#
The second signal whose meaning the receiving program defines.
User2SpawnOptions Type#
Settings for spawn. Every field has a default, so SpawnOptions() pipes all three
streams and inherits the caller’s directory and environment.
type SpawnOptions {
stdin Stdio = Stdio.Pipe
stdout Stdio = Stdio.Pipe
stderr Stdio = Stdio.Pipe
cwd String? = null
env Map[String, String] = Map[String, String]()
}SpawnOptions.cwd#
The child’s working directory; null inherits the caller’s.
cwd String? = nullSpawnOptions.env#
Variables added to or replaced in the inherited environment.
env Map[String, String] = Map[String, String]()SpawnOptions.stderr#
Where the child writes standard error.
stderr Stdio = Stdio.PipeSpawnOptions.stdin#
Where the child reads standard input.
stdin Stdio = Stdio.PipeSpawnOptions.stdout#
Where the child writes standard output.
stdout Stdio = Stdio.PipeStdio Enum#
Where a child’s standard input, output, or error goes, chosen per stream.
spawn("make", [], SpawnOptions(stdout: Stdio.Inherit, stderr: Stdio.Inherit)) lets the
child’s output reach the parent’s terminal while stdin stays piped.
enum Stdio {
Pipe
Inherit
Null
}Stdio.Inherit#
The parent’s own stream, so the child reads or writes it directly.
InheritStdio.Null#
The null device: input is at end of file, output is discarded.
NullStdio.Pipe#
An OS pipe to the parent, read or written through the Subprocess’s stream.
PipeSubprocess Type#
A long-lived child process with live stdin, stdout, and stderr streams. Closing it
kills the child’s process group, joins it, and closes all three streams.
A stream spawned as Stdio.Inherit or Stdio.Null has no pipe: it is already closed, so a read returns end of stream (null) and a write returns EBADF.
opaque type Subprocess {
}Subprocess.close#
Kills the process group, joins the child, kills leftover group members, and closes all three streams. Idempotent; scope exit calls it.
move fn close() Result[Void, Error]Subprocess.kill#
Sends signal to the child’s process group, or its job object on Windows, and does
not wait. The default Signal.Kill ends the child at once. Once the child has
exited it does nothing. A signal the host has no equivalent for returns ENOTSUP;
see Signal for what each one does on each platform.
fn kill(signal Signal = Signal.Kill) Result[Void, Error]Subprocess.max_resident_bytes#
The child’s peak resident set size in bytes, known once wait has returned its
exit status; 0 before that or when the host cannot report it.
fn max_resident_bytes() IntSubprocess.pid#
The operating system id of the child, which kill and send_signal accept.
fn pid() IntSubprocess.stderr#
The child’s standard error as a ReadStream over the OS pipe, with the same blocking and backpressure behavior as stdout.
fn stderr() ReadStream[Bytes]Subprocess.stdin#
The child’s standard input as a WriteStream; writes block when the pipe is full. Closing the stream delivers end-of-input to the child.
fn stdin() WriteStream[Bytes]Subprocess.stdout#
The child’s standard output as a ReadStream over the OS pipe; reads block until output or end-of-file, and nothing is buffered without bound.
fn stdout() ReadStream[Bytes]Subprocess.wait#
Waits for the child to exit and returns its exit status, or -1 for a child ended by a
signal on Unix. Returns ETIMEDOUT if timeout elapses first, leaving the child
running.
fn wait(timeout Duration? = null) Result[Int, Error]cpu_usage Function#
Returns cumulative user and kernel CPU time consumed by this process in microseconds. Platforms without resource accounting return ENOTSUP.
fn cpu_usage() Result[CpuUsage, Error] { ... }get_priority Function#
Returns the scheduling priority of process pid (0 means the calling process) as a
nice-style value, from -20 for highest to 19 for lowest. Windows maps its priority
classes onto this range. A pid outside 0 through 2147483647 returns EINVAL, and
platforms without priorities return ENOTSUP.
fn get_priority(pid Int) Result[Int, Error] { ... }groups Function#
Returns the numeric ids of the supplementary groups of the process. Windows returns ENOTSUP.
fn groups() Result[List[Int], Error] { ... }initialize_groups Function#
Replaces the supplementary group list with the groups of username from the account
database plus gid first. Requires privilege. A failed user lookup returns EIO, a
gid outside 0 through 2147483647 returns EINVAL, and a lack of privilege returns
EACCES.
fn initialize_groups(username String, gid Int) Result[Void, Error] { ... }kill Function#
Sends signal to process pid and does not wait. The default Signal.Kill ends the
process. A positive pid names one process; on Linux and macOS a negative one names
the process group -pid. A pid outside the signed 32-bit range returns EINVAL, a pid
that names no process returns ENOENT, a lack of permission returns EACCES, and a
signal the host has no equivalent for returns ENOTSUP (see Signal). Use
send_signal for a raw signal number, or signal 0 to test that a process exists.
fn kill(pid Int, signal Signal = Signal.Kill) Result[Void, Error] { ... }process_info Function#
Returns the process id, parent id, executable path, arguments, platform, and real and effective user and group ids. Text that is not valid UTF-8 returns ENOTSUP.
fn process_info() Result[ProcessInfo, Error] { ... }replace Function#
Replaces the running process image with program using exactly the given arguments
as argv, where arguments[0] is the program name, and exactly the given
environment. On success it never returns.
program is a path, not a PATH lookup. An empty program, an empty argument list, or NUL
bytes return EINVAL, and exec failures return ENOENT, EACCES, or EIO. ENOTSUP on
Windows.
fn replace(program String, arguments List[String], environment Map[String, String]) Result[Void, Error] { ... }resource_usage Function#
Returns kernel resource counters for this process: CPU times, peak resident size, page faults, block I/O, and context switches. Platforms without them return ENOTSUP.
fn resource_usage() Result[ResourceUsage, Error] { ... }run Function#
Starts program directly, without a shell, searching the PATH, and returns a promise that finishes when it does. arguments are passed after the program name, options.input is written to its standard input, and its output is captured.
Output beyond options.max_output_bytes in total across both streams returns EOVERFLOW, options.timeout returns ETIMEDOUT, and in both cases the child’s process group is killed. Cancelling the calling task also kills it.
options.cwd is the child’s working directory (null inherits the caller’s); options.env adds or replaces variables on top of the inherited environment, and a name that is empty or holds =, or a NUL byte anywhere, returns EINVAL. A cwd that does not exist returns ENOENT. Neither touches the caller’s own directory or environment, so concurrent tasks can run children in different directories.
fn run(program String, arguments List[String] = [], options RunOptions = RunOptions()) Promise[CommandOutput] { ... }send_signal Function#
Sends signal, from 0 through 64, to process pid, a signed 32-bit id; other values
return EINVAL, and the OS decides which signals and permissions are supported.
Signal 0 only checks that the process exists. On Windows, a positive PID supports
signal 0 and forced termination with INT, KILL, or TERM. A pid that names no process
returns ENOENT.
fn send_signal(pid Int, signal Int) Result[Void, Error] { ... }set_groups Function#
Replaces the supplementary group list with the given numeric ids, each 0 through 2147483647. Requires privilege. Invalid ids return EINVAL, a lack of privilege returns EACCES, and Windows returns ENOTSUP.
fn set_groups(groups List[Int]) Result[Void, Error] { ... }set_identity Function#
Sets the real or effective user or group id to id, 0..2147483647; other ids return
EINVAL. Identity changes require OS permission and are ENOTSUP on Windows.
fn set_identity(kind IdentityKind, id Int) Result[Void, Error] { ... }set_priority Function#
Sets the scheduling priority of process pid (0 means the calling process) to a
nice-style value from -20 (highest) through 19 (lowest). A pid outside 0 through
2147483647 or a priority outside that range returns EINVAL. Unix uses nice values;
Windows maps the range to native priority classes.
fn set_priority(pid Int, priority Int) Result[Void, Error] { ... }set_title Function#
Sets the process title shown by tools such as ps. A title with NUL or newline
returns EINVAL, and platforms that cannot rename a process return ENOTSUP. On Linux
and macOS a title longer than the program’s original command line is cut to fit.
fn set_title(title String) Result[Void, Error] { ... }spawn Function#
Starts program directly, without a shell, searching the PATH, and returns a live
Subprocess that its scope closes. arguments follow the program name;
options.stdin, options.stdout, and options.stderr each choose a pipe (the
default), the parent’s own stream, or the null device. Returns EINVAL, ENOENT (no
such program or working directory), EACCES (not executable), or EIO when it cannot
start. Closing the Subprocess, or cancelling the acquiring execution, kills the
child’s process group.
options.cwd and options.env behave as in run.
fn spawn(program String, arguments List[String] = [], options SpawnOptions = SpawnOptions()) Result[Subprocess, Error] { ... }title Function#
Returns the current process title. Platforms that cannot read it return ENOTSUP.
fn title() Result[String, Error] { ... }watch_signals Function#
Observes the native signal numbers in signals: a nonempty list of numbers from 1 through 64, excluding SIGKILL and
SIGSTOP. Other lists return EINVAL. capacity is how many signals are buffered while no read waits, from 1 through
1048576; null uses 128. A number in range may still be unsupported by the OS. Observing a signal does not suppress
host cancellation.
Each read yields the next signal number; the stream never ends on its own. Dropping it unregisters the observer.
Use scope-owned Closeable resources for shutdown cleanup, since cancellation may prevent code after a read from running.
fn watch_signals(signals List[Int], capacity Int? = null) Result[ReadStream[Int], Error] { ... }