Skip to content

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.

ant
let who = Os.args().get(0) ?? "world"
println(try Cmd.new("echo", ["hello", who]).read())
text
hello Ann

No 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:

ant
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())
text
grep fix | wc -l
2

Choosing how to run a command ​

You wantUse
to run a program the user watches or types intoCmd.run
one value a program printsCmd.read, or Cmd.readBytes
the status and both outputs, without failing on nonzeroCmd.capture, or Cmd.captureBytes
the output as it comes, or a program that keeps runningCmd.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:

ant
let step = Cmd.new("sh", ["-c", "echo testing; exit 3"])
eprintln("+ ${step.string()}")
let status = try step.run()
if status != 0 {
  Os.exit(status)
}
text
testing

Cmd.read turns a nonzero status into an Err that carries the command's standard error, and Cmd.capture keeps the status and both outputs:

ant
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()}")
text
Err{ error: Error{ message: "sh: exit status 2: oops" } }
2: data / oops

env is the child's whole environment, so start from Os.environ() to add one variable:

ant
let env = Os.environ()
env["GREETING"] = "hi"
println(try Cmd.new("sh", ["-c", "echo $GREETING"], env: env).read())
text
hi

Cmd.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:

ant
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()}")
text
got one
got two
status 0

A 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:

ant
let stop = Os.interrupt()
let helper = try Cmd.start(Cmd.new("sleep", ["10"]))
defer { helper.stop() }
stop.wait()
println("shutting down after ${stop.reason()}")
text
shutting down after interrupt

Functions 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 null on Windows and WebAssembly

Environment and host ​

Streams and pipes ​

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 Cmd would start, or null

Running to the end ​

Running in the background ​

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