santoku-system
View on LuaRocksprocess spawning and POSIX glue: fork programs or Lua functions across parallel jobs and stream their output as iterators
santoku-system is the framework's process layer. It forks a program or a plain Lua function across one or more jobs and streams the output back as an iterator. It's the engine under toku build hooks, deploy tooling and secrets-injection CLIs.
Details
- santoku-system is built directly on fork, pipe, poll and execvp.
- Requiring santoku.system returns one table. The table merges execute, pread and sh with the santoku.system.posix bindings and everything from Lua's os library.
- So sys.fork and sys.getenv live beside sys.sh.
- Failures raise structured errors through santoku.error, with the OS message and errno.
- Everything here needs a real operating system underneath. So the examples are shown for reading instead of wired to the in-page interpreter.
One merged table
The module puts three layers in one namespace: the high-level execute, sh and pread, the raw POSIX bindings, and stock os.
local sys = require("santoku.system")
print(type(sys.execute), type(sys.sh), type(sys.pread))
print(type(sys.fork), type(sys.pipe), type(sys.execp))
print(type(sys.getenv), type(sys.time), type(sys.exit))
print("cores:", sys.get_num_cores())
Details
- An earlier layer takes precedence on a name clash.
santoku.system.async since santoku-system 3.0.0
santoku.system.async is the native runtime for santoku.async: a poll() loop, a monotonic clock, a timer heap, scopes and semaphores. santoku-socket's sockets, TLS and sh and pread's pipes wait through it, so tasks run while one waits.
local sys = require("santoku.system")
local rt = require("santoku.system.async")
local async = require("santoku.async")(rt)
local done = async.semaphore(0)
for _, ms in ipairs({ 300, 100, 200 }) do
async.spawn(function ()
local lines = sys.sh({ "sh", "-c", "sleep " .. ms / 1000 .. "; echo " .. ms })
print(lines())
done.post()
end)
end
for _ = 1, 3 do
done.wait()
end
Details
- spawn(fn, ...) runs fn as a task up to its first wait, then returns.
- A wait from the main thread runs the loop until that wait ends. When main returns, the process ends and unfinished tasks are dropped.
- A main-thread wait that no fd, timer or task can end raises "santoku.system.async: the main thread waits, and no task or timer can wake it".
- readable(fd, ms) and writable(fd, ms) wait on an fd and return false on timeout. poll(fds, events, ms) waits on several. They serve santoku-socket and santoku-tls.
- kill(s) drops the tasks of s and its children with their waits.
- Files, DNS lookups and sqlite calls block the loop.
- Tasks share one Lua thread. CPU-bound tasks run one after another, and each blocks the loop while it runs. For parallel work, fork processes with sh or pread, or write the work in C with OpenMP.
- Under PUC Lua 5.1, a task can't yield from inside a generic for iterator, so drive sh's iterator with a while loop inside a task.
- sys.pollfds(fds, events, ms) and sys.now() are the C calls under the loop. santoku.system.posix.poll is gone.
execute
execute runs a program to completion. The child inherits the terminal, so its output flows straight through untouched. The call raises if the child exits non-zero, and returns normally otherwise.
local sys = require("santoku.system")
sys.execute({ "git", "status", "--short" })
sys.execute({ "tar", "-C", "dist", "-czf", "release.tar.gz", "." })
Build configure hooks
toku make files commonly shell out to asset tooling from a target's build function. The examples are a CSS build, icon rasterization and dev-only self-signed TLS.
local sys = require("santoku.system")
sys.execute({
"tailwindcss",
"-i", "res/index.css",
"-o", "public/index.css",
"--minify",
})
sys.execute({
"rsvg-convert", "-w", "192", "-h", "192",
"-o", "public/icon-192.png", "res/icons/icon.svg",
})
sys.execute({
"openssl", "req", "-x509", "-nodes", "-days", "365",
"-newkey", "rsa:2048",
"-keyout", "ssl/localhost.key",
"-out", "ssl/localhost.crt",
"-subj", "/CN=localhost/O=DEV ONLY",
})
The sh line iterator
sh forks a child and iterates its stdout line by line, with trailing newlines stripped. The iterator ends when the child exits, and a non-zero exit raises through santoku.error instead.
local sys = require("santoku.system")
for line in sys.sh({ "sh", "-c", "echo a; echo b" }) do
print(line)
end
Details
- A blank line comes back as an empty string.
- Pass skip_blank = true to drop blank lines instead.
One-shot capture
The iterator is a plain function, so one call takes the first line and discards the rest. Deploy tooling probes the toolchain this way.
local sys = require("santoku.system")
local arch = sys.sh({ "uname", "-m" })()
print("arch:", arch)
local symbolizer = sys.sh({
"sh", "-c", "command -v llvm-symbolizer 2>/dev/null || true"
})()
print("symbolizer:", symbolizer)
Details
- The probes read the architecture, the compiler resource dirs, and which symbolizer is on PATH.
Collect and join
Accumulate every line into a buffer to capture a program's whole output as a string. The example is the make engine's JS minifier, which feeds a temp file through esbuild.
local sys = require("santoku.system")
local fs = require("santoku.fs")
local arr = require("santoku.array")
local tmp = fs.tmpname() .. ".js"
fs.writefile(tmp, "function add (a, b) { return a + b; }")
local parts = {}
for chunk in sys.sh({ "esbuild", "--minify", tmp }) do
parts[#parts + 1] = chunk
end
fs.rm(tmp)
print(arr.concat(parts, "\n"))
pread raw events
pread sits beneath sh and returns an iterator of (event, pid, ...) tuples. Every child ends with an exit event that carries a reason and status.
local sys = require("santoku.system")
local it = sys.pread({
"sh", "-c", "echo out; echo err >&2; exit 1",
stderr = true,
})
for ev, pid, a, b in it do
if ev == "exit" then
print(ev, a, b)
else
print(ev, a)
end
end
Details
- stdout and stderr events carry raw chunks, with no line buffering.
Stream options
The iterator watches stdout by default, and stderr only when stderr = true. bufsize caps each read and defaults to BUFSIZ.
local sys = require("santoku.system")
for ev, pid, reason, status in sys.pread({
"sh", "-c", "exit 7",
stdout = false,
}) do
print(ev, reason, status)
end
for ev, pid, chunk in sys.pread({
"sh", "-c", "echo hello",
bufsize = 500,
}) do
print(ev, chunk)
end
for line in sys.sh({ "tr", "a-z", "A-Z", stdin = "fed through stdin" }) do
print(line)
end
Details
- With stdout = false nothing is watched, and the iterator yields only the exit event.
- stdin = string feeds that string to each child's standard input in PIPE_BUF chunks, then closes it.
- sh and pread both take stdin.
- A non-string stdin raises "stdin must be a string".
Failure as data
pread reports a non-zero exit as data instead of raising. A CLI can then collect a child's stderr into a diagnostic and decide what to do with it.
local sys = require("santoku.system")
local arr = require("santoku.array")
local reason, rc, diag = nil, nil, {}
for what, _, r, c in sys.pread({
"sh", "-c", "echo broadcast refused >&2; exit 3",
stdout = true, stderr = true,
}) do
if what == "exit" then
reason, rc = r, c
elseif what == "stderr" then
diag[#diag + 1] = r
end
end
if reason ~= "exited" or rc ~= 0 then
print("failed: " .. arr.concat(diag):gsub("%s+$", ""))
end
Details
- sh raises on a non-zero exit instead.
- The example is a secrets client that collects a helper's failure message.
Probing with execute
execute raises on a non-zero exit, so a pcall around it turns any exit-status idiom into a boolean.
local sys = require("santoku.system")
local err = require("santoku.error")
local found = err.pcall(sys.execute, { "sh", "-c", "command -v git >/dev/null" })
print("git on PATH:", found)
Details
- Check a pid with alive(pid) instead of kill -0, which succeeds on a zombie.
Environment control
The env option calls setenv for each pair in the child before exec, and leaves the parent untouched.
local sys = require("santoku.system")
for line in sys.sh({
"sh", "-c", "echo $GREETING",
env = { GREETING = "hello" },
}) do
print(line)
end
sys.execute({
"luarocks", "make", "lib.rockspec",
env = {
LUAROCKS_CONFIG = "/abs/path/luarocks.lua",
MAKEFLAGS = "--no-print-directory",
},
})
Details
- The make engine drives luarocks this way, and pins LUAROCKS_CONFIG and MAKEFLAGS per invocation.
Parallel jobs
jobs = N forks N copies of the same argv, and one iterator interleaves all their output. job_var exposes each worker's index, 1 to N, as an env var.
local sys = require("santoku.system")
for line in sys.sh({
"sh", "-c", "echo worker $JOB",
jobs = 4, job_var = "JOB",
}) do
print(line)
end
Details
- Under pread, exit events surface per child.
Parallel Lua functions
fn in place of an argv forks a plain Lua closure per job. Each child runs fn(job, opts) in its own process, and its prints stream back through the same iterator.
local sys = require("santoku.system")
for line in sys.sh({
jobs = 4,
fn = function (job)
print("worker " .. job .. " pid " .. sys.pid())
end,
}) do
print(line)
end
Details
- A raised error in the child becomes a non-zero exit.
Throttled atoms
atom(initial, throttle) also records the time of the last take. It sleeps inside the semaphore until at least throttle seconds have passed, so it works as a cross-process rate limiter.
local sys = require("santoku.system")
local fs = require("santoku.fs")
if not sys.atom then
return "atom unavailable on this platform"
end
local next_page = sys.atom(1, 0.5)
for line in sys.sh({
jobs = 4,
fn = function (job)
for _ = 1, 3 do
local page = next_page()
print(job, "fetching page", page)
fs.stdout:flush()
end
end,
}) do
print(line)
end
Details
- N workers that call one API share a single pace.
- The call accepts an optional increment, 1 by default.
Cross-process mutex
mutex() returns a lock function. lock(fn, ...) runs fn under a shared semaphore as a cross-process critical section, and passes fn's return values through.
local sys = require("santoku.system")
local fs = require("santoku.fs")
if not sys.mutex then
return "mutex unavailable on this platform"
end
local lock = sys.mutex()
local a, b = lock(function ()
return 1, 2
end)
print(a, b)
for line in sys.sh({
jobs = 4,
fn = function (job)
lock(function ()
print("job " .. job .. " has the lock")
fs.stdout:flush()
end)
end,
}) do
print(line)
end
Details
- lock releases the semaphore even if fn raises, and the error re-raises after the release.
- Like atom, mutex is unavailable on Android.
Process replacement with execp
execp(prog, argv) replaces the current process through execvp, with a PATH search and argv from the table. It never returns on success, so the next line runs only after a failure with errno.
local sys = require("santoku.system")
local fs = require("santoku.fs")
local err = require("santoku.error")
local payload_env = { API_KEY = "s3cret", REGION = "us-east-1" }
for k, v in pairs(payload_env) do
sys.setenv(k, v)
end
local _, e = err.pcall(sys.execp, "terraform", { "plan" })
fs.stderr:write("terraform: " .. tostring(e) .. "\n")
sys.exit(127)
Details
- A secrets CLI ends this way. It injects secrets with setenv, then execs the user's command.
A supervised child
fork() returns the child pid in the parent and 0 in the child. An ssh-agent forwarding CLI forks, then execs the user's command in the child with execp.
local sys = require("santoku.system")
local fs = require("santoku.fs")
local err = require("santoku.error")
local path = "/tmp/ll-agent.sock"
local pid = sys.fork()
if pid == 0 then
sys.setenv("SSH_AUTH_SOCK", path)
local _, e = err.pcall(sys.execp, "ssh", { "deploy@host", "uptime" })
fs.stderr:write("ssh: " .. tostring(e) .. "\n")
sys.exit(127)
end
local _, reason, status = sys.wait(pid)
print(reason, status)
Details
- On Linux the child also gets SIGHUP if the parent dies.
- The CLI points the child at a private SSH_AUTH_SOCK before the exec.
- The parent serves the agent socket until the child exits.
The raw primitives
The module exports the primitives that sh is built from. pipe() returns read and write fds with close-on-exec, dup2 rewires a child's stdout, read pulls raw bytes, and wait reaps.
local sys = require("santoku.system")
local fs = require("santoku.fs")
fs.flush(fs.stdout)
local r, w = sys.pipe()
local pid = sys.fork()
if pid == 0 then
sys.close(r)
sys.dup2(w, 1)
sys.close(w)
fs.write(fs.stdout, "hello from the child")
fs.flush(fs.stdout)
sys.exit(0)
end
sys.close(w)
print(sys.read(r, sys.BUFSIZ))
sys.close(r)
sys.wait(pid)
local r2, w2 = sys.pipe()
print("wrote:", sys.write(w2, "raw bytes"), "PIPE_BUF:", sys.PIPE_BUF)
print(sys.read(r2, sys.BUFSIZ))
sys.close(r2)
print("reader gone:", sys.write(w2, "x"))
sys.close(w2)
Details
- write(fd, s) writes to a raw fd with SIGPIPE ignored and returns the byte count.
- write returns false when the reader has gone (EPIPE). Other errors raise.
- PIPE_BUF is the largest write that a pipe keeps atomic.
- Flush buffered Lua output before fork, or the child inherits the buffer and prints it again.
Identity, cores and sleep
pid() and ppid() give process identity, and get_num_cores() sizes jobs. sleep(seconds) takes a fraction, and BUFSIZ is exported too.
local sys = require("santoku.system")
local fs = require("santoku.fs")
print("pid:", sys.pid(), "ppid:", sys.ppid())
print("alive:", sys.alive(sys.pid()))
print("cores:", sys.get_num_cores())
print("bufsiz:", sys.BUFSIZ)
sys.sleep(0.25)
fs.flush(fs.stdout)
local pid = sys.fork()
if pid == 0 then
sys.exit(3)
end
local wpid, reason, status = sys.wait(pid)
print(wpid, reason, status)
for line in sys.sh({
"sh", "-c", "echo up",
jobs = sys.get_num_cores(),
}) do
print(line)
end
Details
- ppid() returns the current parent from getppid(). ppid(pid) for another pid reads /proc/<pid>/status, Linux only, and raises when that file is missing.
- Since santoku-system 3.0.1, fork() checks its parent with getppid() and reads no /proc, so it works in a container whose /proc belongs to another pid namespace.
- alive(pid) returns true while the pid exists and still runs. A zombie counts as gone: on Linux it reads the state from /proc, where kill -0 would still succeed. Elsewhere it calls kill(pid, 0).
- wait(pid) returns the pid plus a reason: exited, signaled or stopped with a status, or continued without one.
- The card flushes stdout before fork, so a piped run prints each line once.
Signals and the process table since santoku-system 3.2.0
kill(pid, sig) sends a signal without a kill subprocess. procs() reads /proc and returns one table per process, in place of a ps subprocess.
local sys = require("santoku.system")
local pid = sys.fork()
if pid == 0 then
sys.execp("sleep", { "30" })
end
for _, p in ipairs(sys.procs()) do
if p.pid == pid then
print(p.pid, p.ppid == sys.pid(), p.comm, p.tty, p.starttime)
end
end
print("sent:", sys.kill(pid, "TERM"))
print(sys.wait(pid))
print("again:", sys.kill(pid, 0))
Details
- sig is a number or a name from sys.signals, such as "TERM", "KILL" or "HUP". The name has no SIG prefix.
- kill returns true when the signal was sent, and false when no such process exists (ESRCH).
- kill raises on an unknown signal name and on any other errno, such as EPERM.
- Signal 0 sends nothing and checks only that the pid exists. A zombie still passes, so use alive(pid) to ask whether a process runs.
- A negative pid signals that process group, as kill(2) does.
| procs field | holds |
|---|---|
| pid, ppid | the process and its parent |
| comm | the command name from /proc/<pid>/stat, at most 15 bytes |
| tty | the controlling terminal's device number, 0 for none |
| starttime | the start time in clock ticks after boot, field 22 of /proc/<pid>/stat |
- procs skips a process that exits while it reads, so the list is a snapshot with no fixed order.
- procs is Linux only and raises elsewhere.
Host and terminal facts since santoku-system 3.2.0
uname() returns the kernel's identity as a table, in place of a uname subprocess. isatty(fd) tells whether an fd is a terminal, in place of test -t.
local sys = require("santoku.system")
local u = sys.uname()
print(u.sysname, u.release, u.machine)
if sys.isatty(0) then
print("stdin is a terminal")
end
Details
- The uname table has sysname, nodename, release, version and machine, the fields of uname(2).
- isatty returns false for a pipe, a file, a socket and a closed fd.
- isatty raises on a negative fd.