docs

您正在閱讀 v0.1.2 的文件。Nabi 0.1.2 已停止支援。 最新版本:v0.1.3 →

本頁尚未翻譯,以下為英文原文。

#3.6. process:: - child processes

本頁內容

The std::process module spawns child processes and handles signals. Its basic skeleton follows Rust's Command builder pattern, hardened with modern safeguards on top: pidfd, kill_on_drop and a posix_spawn fast path.

#3.6.1. Command builder

The first thing you meet is the Command struct, the blueprint of a child process. All settings (the program to run, arguments, environment variables, how standard I/O is connected) are built up step by step before spawning.

Path parameters follow the tier-wide argument conventions (Path is P: AsPath).

A builder method returns the changed command and leaves the one it was called on as it was, so copies of a Command are independent: after let a = base.arg("x"), base has no x. A Command is not affine although a Stdio::File in it is (2.13.4): that one file is the exception, shared by every copy (below). A builder call whose result is dropped (base.arg("x");) changes nothing and warns (#[must_use]).

Stdio has four branches: Inherit, which passes on the parent's fd; Null, which discards output entirely; Piped, for two-way communication; and File, which plugs in an open file.

A File moved into Stdio::File belongs to the command, not to the program: the move consumes it, as any move of a File does (2.13.4), and the program does not close it. Running the command (spawn, output, status and their _async twins) closes the parent's copy right after the child is started, and also when starting it fails; the child keeps its own. A failed close there is the run's IoError: the child, already started, is killed and reaped first, so no Child is lost. A copy of a command whose file an earlier run closed fails with InvalidInput instead of running; give each run its own file (File::try_clone). A command that never runs leaves its file open until the program exits: the collector frees memory but closes nothing.

A Stdio holding a file is affine too: the builder call it is given to moves it into the command. Giving one Stdio::File value to two commands, or to two streams of one command (.stdout(s).stderr(s)), is compile error E0133; give each its own file (Stdio::File(try f.try_clone())). Stdio::Inherit, Null and Piped hold nothing and may be given any number of times. Stdio implements Close: a Stdio::File never given to a command is closed by the program (try s.close()), as its File would be.

#run

nabi
pub fn run<P: AsPath>(program: P, args: List<str> = []) throws (IoError | ExitStatusError | Utf8Error) -> str;

The convenient form over Command: runs program with args as Command::output does and returns its stdout as text. A non-success status throws ExitStatusError (status(), stderr() as text with invalid UTF-8 replaced, message()); stdout that is not UTF-8 throws Utf8Error. let out = try process::run("git", ["log", "-1"]); (Python's subprocess.run(.., check=True, capture_output=True, text=True).stdout).

#3.6.2. Child

When spawn succeeds, it returns a Child, the handle to the running process. Through it you can access the standard I/O streams, wait for exit, or send signals.

The exit result is held in the opaque type ExitStatus. If code() is none, the process was terminated by a signal on unix, and signal() (ExitStatusExt, in the prelude on unix) names it as a Signal.

#3.6.3. Examples

As the last example shows, binding a Child with kill_on_drop enabled in using cleans up the child even on flows such as error propagation or early return. Drop issues the kill where the owner releases the Child: at the end of the using block, or where its owner leaves scope (2.13.4). ChildStdin / ChildStdout / ChildStderr are file handles of the pipes and are read and written the same way as File. The Child holds its Piped streams until take_stdin / take_stdout / take_stderr hand one over, leaving none; from then on the taker owns the pipe and must close it, like a File. The pipes never taken close where the Child is released. wait closes a stdin still held by the Child first, so a child reading to end of input can finish; a taken stdin is the taker's to close before wait.

A Child is affine (2.13.4): one owner holds its pipes and waits on it. To stop the child from elsewhere while the owner waits (a timeout, a shutdown signal), take a ChildHandle with handle() and send it to the other thread or task. A handle owns nothing: no pipe, no wait, nothing to close; it only signals. wait / try_wait reap the child only after the send_signal / kill calls in flight through handles return, so a signal never reaches a pid or pidfd that was reused; a send_signal or kill once the child has ended and is being reaped is a no-op.

nabi
let child = try Command::new("server").spawn();
let h = child.handle();
let timer = task::spawn(async {
    await task::sleep(Duration::secs(30));
    try h.kill() catch _ {};
    0
});
let status = try await child.wait_async();

#3.6.4. Modern additions - pidfd / posix_spawn / CLOEXEC

On top of the builder pattern, the standard library adds several modern reinforcements. What each means and what it achieves:

FeatureMeaningEffect
posix_spawn fast pathA syscall instead of fork+execFaster spawn from huge processes
pidfd (Linux 5.3+)Track by fd instead of pidrace-free signal
CLOEXEC defaultEvery fd is close-on-exec automaticallyPrevents fd leaks
kill_on_dropKill where the owner releases itPrevents process leaks

These decisions consistently aim at reducing fd leaks, process leaks and signal races.

With Command::env, the program is still looked up on the parent's PATH, not the child's.

#3.6.5. Signal handling (advanced)

Going a level deeper, there are the signal handling functions.

An on_signal handler does not run in signal context (inside a signal handler). The runtime receives the signal and hands it to a dedicated dispatcher thread nabi-signal, where the handler runs like an ordinary function. The handler must therefore be Send; it is kept and called once per signal, so it is also Sync. It may allocate or take locks. Calling on_signal again for the same signal replaces the handler. Signal names the signal on every OS. process_group(pgid) (CommandExt, unix) puts the child in that process group (0 means a new group with the child's pid).

On Windows, console events map to signals: Ctrl-C → Interrupt (2), console close / logoff / shutdown → Hangup (1). Ctrl-Break has no Signal; os::windows::process::on_ctrl_break routes it (3.10.7). send_signal sends only Signal::Kill, as TerminateProcess, and raise raises only Interrupt and Hangup; any other Signal is an IoError (Unsupported), and on_signal of a signal other than Interrupt or Hangup is a SignalError.

Most users never need to touch this. These tools become necessary only where signals must be faced head-on, such as daemons, servers and interactive CLIs.

#3.6.6. Platform availability

Per-platform support:

Itemlinuxmacoswindowswasi
Command::spawn✓✓✓✗
posix_spawn✓✓(CreateProcess)✗
pidfdlinux 5.3+ (os::linux)✗✗✗
kill_on_drop✓✓✓✗
signal handler✓✓(limited)✗
process::id()✓✓✓panics (wasm32)

On wasm32 targets the items marked ✗ fail at run time with IoErrorKind::Unsupported.

Found a mistake? Edit this page on GitHub. Last updated