docs

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

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

#Child processes

本頁內容

Run external programs such as echo, a shell pipeline and tr with process::run and std::process::Command, and work with their output, exit codes, environment variables and standard input.

#Code

#Walkthrough

  • process::run(program, args) runs a program to the end and returns its stdout as text; a failing exit status throws an ExitStatusError that carries stderr (process::run). main declares no throws: an error it lets through is printed and the program exits with status 1.
  • Command is a builder. Methods such as args, env, current_dir and stdin return the updated command, so calls chain on one line, ending with one of output(), status() or spawn() (3.6.1 Command builder).
  • output() waits for the child to finish and collects both stdout and stderr into an Output. It drains both pipes together, so the child never stalls on a full pipe. str::from_utf8 turns the bytes into a string.
  • The pipe (|) is handled by sh -c, not by nabi. It is the simplest option when you need shell syntax.
  • env adds a variable for the child only, and env_clear empties the inherited environment. The parent's environment does not change.
  • spawn() returns a Child without waiting. The Child holds the pipes opened with Stdio::Piped until you take them: child.take_stdin() hands over the stdin pipe and leaves none behind, so the pipe has one owner, you. Pipes you never take close when the Child is released. Write to stdin, send EOF with close(), then read stdout, close it too, and wait(). A pipe's close can fail, so the compiler asks for it rather than closing it for you.
  • Copies of a Command are independent: a builder method returns a changed copy, so base.arg("hi") leaves base as it was, and one base command can start several variants. A builder call whose result is dropped warns, since it changes nothing.
  • signal() comes from ExitStatusExt in std::os::unix::process. On Linux and macOS it is in the prelude, so it needs no use; on Windows it does not exist (3.10 os::).
  • A missing executable throws an IoError. try ... catch e { ... } catches it on the spot and substitutes a default (3.14 Error control flow, Errors).

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