Skip to content
Weaverv0.5.0

Programs and processes

Module weaver.process: its API, wv doc weaver.process.

weaver.process covers both ends: the program’s own process, how it ends and the signals it receives, and the programs it launches.

main takes nothing, the raw arguments, fn main(args: String[]), or a type parsed from them; weft/cli derives that one, its options and help, from a record marked #Cli.

  • main returning normally exits with 0.
  • An error out of main, fn main() ! IoError, is printed and exits with 1.
  • main returning Exit says which: Exit.success, Exit.failure, Exit.code(3).
  • A panic exits with 101.
  • Process.exit(3) exits from anywhere, after the using and defer of the task; Process.exitNow without them.

Process.id(), Process.executable(), the path of the running program, and Process.which("git"), a program found in PATH, say where the program stands. Its environment is weaver.env’s, Env.get("HOME").

A Command is a value, built step by step, then run:

import weaver.process.{Command}
val st = Command.new("git").args(["fetch", "--quiet"]).dir(repo).status()!
if !st.success() { fail "git fetch: exit ${st.code}" }
val out = Command.new("git").args(["rev-parse", "HEAD"]).output()!
val head = (out.stdout.utf8() ?? "").trim()
  • status() runs it, its standard streams the program’s own, and gives its Status: code, None if a signal killed it, then in signal.
  • output() runs it and collects what it writes, stdout and stderr, beside its status.
  • arg, args, dir, env(name, value), clearEnv() set what it receives; no shell is involved, so an argument is never split or expanded. A shell is asked for explicitly, Command.new("sh").args(["-c", script]).
  • A program that is not found fails with NotFound; one that runs and fails is a status, not an error.

spawn() starts it and returns a Child, a resource: it is waited for, or killed then waited for, before its block ends.

using child = Command.new("cat").stdin(.piped).stdout(.piped).spawn()!
if child.takeStdin() is Some(using input) {
input.write("in the pipe")!
}
val buf = mut Bytes.filled(64, with: 0)
if child.takeStdout() is Some(using out) {
val n = out.read(&buf)!
print(buf[..n].utf8() ?? "")
child.wait()!
}
  • stdin, stdout, stderr each take .inherit, the default, .piped, which takeStdin() and the others hand over, or .null.
  • kill() sends kill, kill(.terminate) asks politely; wait() gives the status.
  • group() starts it in a process group of its own, and killGroup(.terminate) reaches what it started in turn.

Process.signals([.interrupt, .terminate]) watches signals instead of letting them stop the program: watch.next()! waits for the next one, in a task of its own for a server that shuts down cleanly.