Processes and the OS
Two namespaces cover a program's place in the operating system. Os is the program's own process: its arguments, environment, standard streams, exit status, and interrupts. Cmd runs other programs. A Cmd is a record that says what to run, and the function you call on it says how: in the foreground, for its output, or in the background.
let who = Os.args().get(0) ?? "world"
println(try Cmd.new("echo", ["hello", who]).read())hello AnnNo shell runs a command, so its arguments arrive as they are. Join commands with Cmd.pipe instead of |, and every function that runs a Cmd runs the pipeline too:
let fixes = Cmd.pipe([Cmd.new("grep", ["fix"]), Cmd.new("wc", ["-l"])])
println(fixes.string())
let count = try fixes.read(input: "fix a\nadd b\nfix c\n")
println(count.trim())grep fix | wc -l
2Choosing how to run a command
| You want | Use |
|---|---|
| to run a program the user watches or types into | Cmd.run |
| one value a program prints | Cmd.read, or Cmd.readBytes |
| the status and both outputs, without failing on nonzero | Cmd.capture, or Cmd.captureBytes |
| the output as it comes, or a program that keeps running | Cmd.start with Os.openPipe, then Cmd.wait |
Cmd.run gives the command the program's own streams and returns its status, so a script can pass a failure on with Os.exit. A nonzero status is Ok here, not Err:
let step = Cmd.new("sh", ["-c", "echo testing; exit 3"])
eprintln("+ ${step.string()}")
let status = try step.run()
if status != 0 {
Os.exit(status)
}testingCmd.read turns a nonzero status into an Err that carries the command's standard error, and Cmd.capture keeps the status and both outputs:
println(Cmd.new("sh", ["-c", "echo oops >&2; exit 2"]).read())
let out = try Cmd.new("sh", ["-c", "echo data; echo oops >&2; exit 2"]).capture()
println("${out.status}: ${out.stdout.trim()} / ${out.stderr.trim()}")Err{ error: Error{ message: "sh: exit status 2: oops" } }
2: data / oopsenv is the child's whole environment, so start from Os.environ() to add one variable:
let env = Os.environ()
env["GREETING"] = "hi"
println(try Cmd.new("sh", ["-c", "echo $GREETING"], env: env).read())hiCmd.start returns as soon as the command runs. Give it the writing end of a pipe to read the output line by line, and close your copy of the writing end, so reads reach end of file once the command exits:
let out = try Os.openPipe()
defer { out.read.close() }
let job = try Cmd.start(Cmd.new("sh", ["-c", "echo one; echo two"]), stdout: out.write)
try out.write.close()
while true {
let line = try out.read.readLine() ?? break
println("got ${line}")
}
println("status ${try job.wait()}")got one
got two
status 0A command started in the background keeps running when the script ends. Stop it in a deferred block. Here the script runs a helper until Ctrl-C, which Os.interrupt turns into a done context instead of the end of the run:
let stop = Os.interrupt()
let helper = try Cmd.start(Cmd.new("sleep", ["10"]))
defer { helper.stop() }
stop.wait()
println("shutting down after ${stop.reason()}")shutting down after interruptFunctions by job
Arguments and identity
- Os.args: the arguments after the program path
- Os.program: the program path, as the command gave it
- Os.pid: this process's id
- Os.uid, Os.gid: the effective user and group ids, or
nullon Windows and WebAssembly
Environment and host
- Os.env: one variable, or
nullwhen it is not set - Os.environ: every variable, as a new map
- Os.platform, Os.arch: the operating system and processor, by Go's names
- Os.hostname: the host's name
- Os.cpus: the number of CPUs the program may use at once, the limit for CPU-bound
Parallelwork - Os.cwd: the working directory
- Os.home: the user's home directory
- Os.configDir, Os.cacheDir: where programs keep configuration and what can be made again
Streams and pipes
- Os.stdin, Os.stdout, Os.stderr: the standard streams, as handles
- Os.openPipe: two connected handles, as an Os.Pipe
Ending the process
- Os.exit: end the process now with a status; no deferred block runs
- Os.interrupt: a context done at Ctrl-C, SIGINT, or SIGTERM
Building commands
- Cmd.new: a command from a program, its arguments, a directory, and an environment
- Cmd.pipe: commands joined as a shell's
|joins them, as a Cmd.Pipeline - Cmd.string: a command as a shell-quoted line for a log
- Os.which: the path of the program a
Cmdwould start, ornull
Running to the end
- Cmd.run: run in the foreground with the program's streams, and return the status
- Cmd.read: the standard output as text without one final newline,
Erron a nonzero status - Cmd.readBytes: the standard output as bytes, exactly as written
- Cmd.capture: the status and both outputs as text, in a Cmd.Output
- Cmd.captureBytes: the same, with standard output as bytes, in a Cmd.OutputBytes
Running in the background
- Cmd.start: start a command with the handles given, and return a Cmd.Process
- Cmd.wait: the status once the command has exited
- Cmd.kill: send a signal by name
- Cmd.stop: SIGTERM, then SIGKILL after a grace period
- Cmd.pid: the process id of the last stage
See also
Os · Cmd · Files and paths · Concurrency · File.Handle · Run a command and capture its output · Stream a command's output · Handle Ctrl-C · Build a pipeline · Stop or time out a process · Os.args · Read environment variables and standard directories · Read standard input line by line · Os.exit
