23 Processes, Streams and Script Utilities

stardust run FILE -- ARG... executes a script with filesystem, process, stream, network and terminal access. It prints only explicit output; it is stardust eval --quiet, and stardust eval also prints the result of each form. A returned #err ends the script with status 1; (processes/exit 7) ends it with status 7. A shebang on the first line is accepted. A script uses a library file with import: (import {nrepl "lib/nrepl"}) in tools/client.dust names tools/lib/nrepl.dust (Files). These features also work with database storage (Script runner). Plugin selection controls which services are available, including secure randomness.

The io plugin enables these services in eval, run, repl and nrepl. The CLI selects it, with its capabilities, unless --config names a configuration without it. Embedded hosts select grants for each evaluation. Captured functions and retained handles do not retain grants. These grants permit OS access; they are not a filesystem or process sandbox. Process, I/O, TCP and terminal operations currently support Linux. Process creation requires Linux 5.11 or later. Other hosts return #err <script unsupported>. Pure utilities remain available.

23.1. Processes

Signature Result
(processes/run argv [options]) Captured output and final status; closes the child
(processes/start argv [options]) A process record with opaque process, stdin, stdout and stderr handles
(processes/poll child) Current status without waiting
(processes/wait child [options]) Exit status, or timeout without killing the child
(processes/communicate child [input [options]]) Concurrent input/output and final status; closes the child
(processes/close child) Kill its remaining process group, reap, close its pipes
(processes/signal child number) Send signal 1–64 to the child
(processes/kill child) Send SIGKILL to the child
(processes/signal-group positive-group-id number) Signal an OS process group
(processes/exit [code]) End script evaluation, default status 0
(processes/on-exit f) Register a zero-argument shutdown hook; return null
(processes/shell/quote text) One quoted POSIX shell argument; does not execute it

argv is a nonempty list of strings, passed directly without a shell. Use an explicit shell argv when needed. processes/shell/quote quotes one POSIX shell argument; it does not execute it.

Start/run options are cwd, env, clear-env, stdin, stdout, stderr, session, terminal and disable-core-dumps. Boolean options accept booleans or tag syntax, such as {<clear-env>}. env is a map of text values; null removes an inherited name. clear-env defaults to false. Executables without slashes are resolved using the child's PATH. cwd defaults to the session's current directory. Child core dumps are disabled by default.

A stream option attaches an existing opaque stream instead of creating a pipe. terminal must be a PTY handle and also creates a session with that controlling terminal. Every child has its own process group. terminals/start-session has the same arguments as processes/start and always creates a session.

Only processes/run also accepts input and timeout in its options. processes/communicate accepts input separately. Input is text or Bytes; output is always Bytes. Input cannot be combined with an attached stdin stream. Both drain stdout and stderr while writing input, avoiding the usual full-pipe deadlock. They return status, pid, code, signal, stdout and stderr. status is <exited>, <signaled> or <timeout>; poll can also return <running>. code or signal is null when unavailable. Timeout output contains the bytes captured so far; cleanup kills any remaining group members.

wait and communicate options contain only timeout, a nonnegative duration. No timeout means wait until completion or cancellation; zero means an immediate deadline. A timed-out wait leaves the process usable. wait alone does not drain pipes: use communicate when output could fill them. poll and wait retain the exit status until close or communicate releases the child.

(def child (processes/start ["/bin/sh" "-c" "cat; printf diagnostic >&2"]))
; communicate feeds input while draining both outputs. It closes the child.
(def result (processes/communicate child "Arrakis\n" {timeout #dur "PT60S"}))
(tests/equal <exited> (get result "status"))
(tests/equal 0 (get result "code"))
(io/stdout/print (encoding/decode "utf8" (get result "stdout")))
(io/stderr/println (encoding/decode "utf8" (get result "stderr")))
Signature Behavior
(processes/env/get name) Text or null if absent
(processes/env/all) Snapshot of the host environment
(processes/cwd/get) Current session directory
(processes/cwd/set path) Validate and set session directory; return its absolute path

The current directory belongs to the session. It affects child creation and relative fs/ paths without changing the host process directory. Environment operations only read the host environment; overrides are per child.

23.1.1. Shutdown hooks

(processes/on-exit f) registers a zero-argument function and returns null. stardust eval and stardust run call hooks in reverse registration order before closing streams and terminating owned child processes. Hooks run after normal completion, processes/exit, evaluation errors, and handled INT, TERM, HUP or QUIT signals. They retain captured values and the script's OS access.

(processes/on-exit (fn [] (io/stdout/println "first")))
(processes/on-exit (fn [] (io/stdout/println "second")))
(io/stdout/println "body")

This prints body, then second, then first. A hook error is reported and the remaining hooks still run. An otherwise successful script then exits with status 1; an existing nonzero status or terminating signal is preserved. Registering hooks or calling processes/exit during shutdown is an error.

The complete shutdown phase shares a one-second wall-time and CPU budget, or the script's lower configured CPU budget. The script's memory budget still applies. Exhaustion or cancellation can stop the remaining hooks. Blocking file/device operations can delay cancellation until they return. SIGKILL and other forced process termination cannot run hooks.

23.2. Streams and TCP

Signature Behavior
(io/read stream count [options]) At most count Bytes, null at EOF
(io/write stream text-or-bytes [options]) Number of bytes written, possibly partial
(io/wait-readable stream [options]) Boolean; EOF also counts as readable
(io/close stream) Close the handle
(io/open path) Open a file as a read-only stream
(io/stdin/open) Open a persistent standard-input stream
(io/stdin/read [count [options]]) Read standard input; default maximum 65536 Bytes
(io/stdout/print values...) Concatenate str representations to stdout
(io/stdout/println values...) As print, followed by newline
(io/stderr/print values...) As print, to stderr
(io/stderr/println values...) As println, to stderr
(net/tcp/connect host port [options]) A bidirectional stream

Options contain only timeout. A read/write timeout is #err <script timeout>; wait-readable instead returns false. A zero-count read returns empty Bytes, not EOF. Each call writes at most 4096 bytes; loop over the remaining bytes. Text is UTF-8; Bytes can contain arbitrary octets. TCP supports literal IPv4, literal IPv6 and "localhost", with a separate port 1–65535. DNS lookup is not implemented. TCP connection timeout also returns a script timeout error.

23.2.1. Buffered readers

Use a buffered reader to process input incrementally. It retains unread bytes between calls instead of reading the whole input into a list.

Signature Behavior
(io/reader [source [options]]) Buffer a stream or file path; omitted or null source opens stdin
(io/read reader count [options]) At most count Bytes; consume buffered bytes first
(io/read-line reader [options]) Next UTF-8 line without its terminator; null at EOF
(io/peek reader count [options]) Up to count Bytes without consuming them; null at EOF
(io/discard reader count [options]) Consume up to count bytes; return the number discarded
(io/reduce-lines f initial reader [options]) Call (f accumulator line) for each remaining line
(io/close reader) Release buffered data and close an owned source

Constructor options contain only buffer-size, a positive byte count; the default is 65536. peek requires a count no larger than buffer-size and returns fewer bytes only at EOF. Zero-count read and peek return empty Bytes. Discard returns zero at EOF. Counts must be integers from 0 through 2147483647.

Read-line accepts LF, CRLF and CR terminators. Blank lines return an empty string. A final unterminated line is returned once; a final terminator does not create another line. Lines can exceed the buffer size and are bounded by the session's memory budget. Invalid UTF-8 returns an error; byte reads accept any octets. A line terminator, including both bytes of CRLF, is consumed before the next read, peek or discard.

Operation options contain only timeout, applied separately to each underlying read. A timed-out line read retains its partial line for a retry. Discard can advance before a timeout. A reducer returns its final accumulator or stops at an error returned by f. It does not close the reader.

A reader opened from a path or stdin owns its stream. A reader constructed from an existing stream borrows it; closing that reader leaves the stream open. Use the reader exclusively while it is active: direct reads from its source would bypass buffered bytes. Close the reader before closing or draining its source through process operations. Readers cannot be serialized or moved to another session. File paths follow the session's current directory and require filesystem access as well as stream access.

This script counts standard-input lines without retaining their contents:

; Count lines incrementally without retaining a list of their contents.
(def reader (io/reader))
(def total (io/reduce-lines (fn [n line] (+ n 1)) 0 reader))
(io/close reader)
(io/stdout/println total)

For a file, use (io/reader "names.txt"). For subprocess output, use (io/reader (get child /stdout)). The same operations accept a reader over a TCP stream returned by net/tcp/connect.

23.2.2. Framed input

Import lib/nrepl.dust, as (import {nrepl "../lib/nrepl"}) does in a script of tools/. It exports:

Signature Result
(nrepl/read-frame reader [options]) The next wire dictionary as Bytes, or null at EOF
(nrepl/read-message reader [options]) The next dictionary as a map with UTF-8 text values
(nrepl/write-message writer message [options]) Send a dictionary, completing partial writes

Readers and writers follow the bencode stream rules above. Options contain timeout. Reading never consumes the next frame; a buffered reader keeps any bytes fetched ahead. One request can produce multiple replies: read through the reply whose status contains "done". These helpers do not close streams.

This example sends an evaluation to a local nREPL server. Pass its port as the script argument and load lib/nrepl.dust:

; Run with a local nREPL server's port.
(import {nrepl "../../lib/nrepl"})
(def port (int (get (cli/args) 0)))
(def socket (net/tcp/connect "127.0.0.1" port {timeout #dur "PT60S"}))
(def reader (io/reader socket))
(tests/assert (> (nrepl/write-message socket {op "eval" id "example" code "(+ 1 2 3)"}) 0))
(def value (nrepl/read-message reader {timeout #dur "PT60S"}))
(tests/equal "example" (get value /id))
(tests/equal "6" (get value /value))
(def complete (nrepl/read-message reader {timeout #dur "PT60S"}))
(tests/equal ["done"] (get complete /status))
(io/close reader)
(io/close socket)
(io/stdout/println "6")

23.3. Terminal and job control

Signature Behavior
(terminals/pty/open) {master handle slave handle}
(terminals/start-session argv [options]) Start a process in a new session
(terminals/foreground-group stream [group-id]) Get/set foreground process group
(terminals/attributes stream [attributes]) Get/update termios attributes
(terminals/resize stream dimensions) Set rows and columns, each 1–65535
(terminals/character-width text) Grapheme display width

Attributes are input, output, control and local integer flag words, input-speed and output-speed OS baud constants, and controls Bytes. The getter returns a complete map suitable for restoration. A setter changes only the supplied fields. Setting a foreground group requires membership in that terminal's session, as enforced by the OS. PTY operations change that terminal, not the host's interactive terminal. character-width requires no terminal capability.

(def pty (terminals/pty/open))
(def original (terminals/attributes (get pty "slave")))
(terminals/resize (get pty "master") {rows 24 columns 80})
(def child
  (terminals/start-session ["/bin/sh" "-c" "test -t 0 && printf Ready"]
    {terminal (get pty "slave")
     stdin (get pty "slave")
     stdout (get pty "slave")
     stderr (get pty "slave")}))
(io/close (get pty "slave"))
(tests/equal "Ready" (encoding/decode "utf8" (io/read (get pty "master") 5 {timeout #dur "PT60S"})))
(tests/equal 0 (get (processes/wait child {timeout #dur "PT60S"}) "code"))
(processes/close child)
(io/close (get pty "master"))

23.4. Resource ownership and interruption

Each session permits at most 128 streams and 32 child processes. Handles cannot be serialized or used in another session. Close is explicit; a second close is an error. Unattached standard streams are private pipes. Attaching an existing stream does not transfer its ownership. communicate and process cleanup close only the private pipes they created.

Ending a session closes its streams and terminates its child process groups. A failed evaluation releases resources it created; earlier resources remain open until closed or the session ends. Filesystem changes and other OS effects already performed remain in place. I/O buffers count toward the memory budget. Cancellation can wait for a file or device operation to complete.

The CLI forwards INT, TERM, HUP and QUIT to owned groups and waits for each child to exit. A child that has not exited after 2 seconds receives SIGKILL. The CLI then terminates by that signal.

23.5. Arguments, timing and checks

Signature Behavior
(cli/args) Script arguments, excluding executable and script path
(scripts/path) Absolute script path, or empty text outside a configured script
(cli/parse specification [argv]) {options {...} arguments [...]}; argv defaults to cli/args and requires io when omitted
(cli/command specification [argv]) Named positional arguments and options in one map; handles help and usage exits
(cli/format-opts options) Sorted option help, including descriptions, defaults and the reserved help option
(time/monotonic) Monotonic duration for elapsed-time subtraction
(time/sleep duration) Cancellable nonnegative delay
(formats/csv/row values) CSV row with quoting and CRLF terminator
(stats/median numbers) Sorted-copy median, preserving input
(tests/assert value [message]) Value on success; fatal assertion on false, null or error
(tests/equal expected actual [message]) True or fatal assertion
(tests/fail [message]) Fatal assertion

Each cli/parse option has type (<string> by default, <int>, <float> or <boolean>), optional one-character short, default, required and multiple. desc supplies help text. Multiple options collect a list and cannot have a default. Long options accept --count=10 or --count 10; short options can cluster, such as -vn10. -- ends option parsing. Unknown, missing and repeated non-multiple options are errors. Int parsing checks the full signed 64-bit range; float parsing rejects infinities and NaNs.

cli/command adds the script entry-point behavior. Its specification has a required name and optional doc, args (positional names), variadic and options (the same specification as cli/parse). Positional names are required; with <variadic>, the last name collects one or more remaining arguments. Names must be unique across options and positional arguments. The returned map contains named arguments and parsed option values together.

(cli/command
  {name "verify.dust"
   args ["directory" "logs"]
   <variadic>
   options {count {short "n" type <int> default 3 desc "Repetitions"}}}
  ["-n5" "suite" "first.log" "second.log"])
; {count 5 directory "suite" logs ["first.log" "second.log"]}

Omit argv in a script to read its command-line arguments. -h and --help print generated usage, documentation and option help, then exit with status 0. They are reserved by cli/command. -- ends option parsing, allowing a literal --help positional argument. Argument errors print a diagnostic and usage to stderr and exit with status 2. Invalid command definitions produce ordinary errors; resource limits remain fatal. cli/parse continues to return errors without printing or requesting an exit.

An option's validate field accepts an ordinary function or a map containing pred and an optional message. Validation runs after all type conversions succeed, in option-name order. It checks defaults and false boolean values; missing optional values and absent repeated options are skipped. A repeated option supplies its complete list to the predicate.

(cli/command
  {name "generate.dust"
   options {iterations {type <int>
                        default 100
                        validate {pred (fn [n] (and (> n 0) (= 0 (rem n 2))))
                                  message "must be positive and even"}}}}
  ["--iterations" "10"])
; {iterations 10}

A false or null predicate result rejects the value. For example, --iterations 3 reports --iterations: must be positive and even; got 3, prints usage, and requests exit status 2. Without a custom message, the text is validation failed. An error returned by the predicate propagates through cli/parse; cli/command reports it as an argument failure. Assertions, cancellation and resource failures remain fatal and retain their original status. Predicates can capture lexical bindings. cli/format-opts shows option descriptions and defaults without running them.

DUST
{typed (cli/parse {count {type <int> validate (fn [n] (> n 0))}} ["--count" "5"])
 default (cli/parse {count {type <int> default 4 validate (fn [n] (= 0 (rem n 2)))}} [])
 rejected-default (cli/parse {count {type <int> default 3 validate {pred (fn [n] (= 0 (rem n 2))) message "must be even"}}} [])
 rejected (cli/parse {count {type <int> validate (fn [n] (> n 0))}} ["--count" "0"])
 predicate-error (cli/parse {count {type <int> validate (fn [n] (/ n 0))}} ["--count" "5"])
 callback-closure (let [minimum 3] (cli/parse {count {type <int> validate (fn [n] (> n minimum))}} ["--count" "5"]))
 missing (let [calls []] [(cli/parse {count {type <int> validate (fn [n] (lists/append calls n) true)}} []) calls])
 false-default (cli/parse {flag {type <boolean> validate (fn [value] (not value))}} [])
 multiple (cli/parse {item {<multiple> validate (fn [values] (= 2 (count values)))}} ["--item" "Paul" "--item" "Chani"])
 bad-predicate (cli/parse {count {validate {pred 42}}} [])
 bad-message (cli/parse {count {validate {pred :int? message 42}}} [])
 unknown (cli/parse {count {validate {pred :int? typo true}}} [])
 command (cli/command {name "example" options {count {type <int> default 4 validate {pred (fn [n] (= 0 (rem n 2))) message "must be even"}}}} [])
 type-before-predicate (let [calls []] [(cli/parse {count {type <int> validate (fn [n] (lists/append calls n) true)}} ["--count" "wrong"]) calls])
 false-message (cli/parse {count {validate {pred :int? message false}}} [])
 missing-multiple (let [calls []] [(cli/parse {item {<multiple> validate (fn [xs] (lists/append calls xs) true)}} []) calls])}
→
Canonical DUST
{bad-message (cli/parse {count {validate {message 42 pred :int?}}} [])
 bad-predicate (cli/parse {count {validate {pred 42}}} [])
 callback-closure (let
                    [minimum 3]
                    (cli/parse {count {type <int> validate (fn [n] (> n minimum))}} ["--count" "5"]))
 command (cli/command
           {name "example"
            options {count {default 4
                            type <int>
                            validate {message "must be even"
                                      pred (fn [n] (= 0 (rem n 2)))}}}}
           [])
 default (cli/parse {count {default 4 type <int> validate (fn [n] (= 0 (rem n 2)))}} [])
 false-default (cli/parse {flag {type <boolean> validate (fn [value] (not value))}} [])
 false-message (cli/parse
                 {count {validate {<!message>
                                   pred :int?}}}
                 [])
 missing (let
           [calls []]
           [(cli/parse {count {type <int> validate (fn [n] (lists/append calls n) true)}} []) calls])
 missing-multiple (let
                    [calls []]
                    [(cli/parse
                       {item {<multiple>
                              validate (fn [xs] (lists/append calls xs) true)}}
                       [])
                     calls])
 multiple (cli/parse
            {item {<multiple>
                   validate (fn [values] (= 2 (count values)))}}
            ["--item" "Paul" "--item" "Chani"])
 predicate-error (cli/parse {count {type <int> validate (fn [n] (/ n 0))}} ["--count" "5"])
 rejected (cli/parse {count {type <int> validate (fn [n] (> n 0))}} ["--count" "0"])
 rejected-default (cli/parse
                    {count {default 3
                            type <int>
                            validate {message "must be even"
                                      pred (fn [n] (= 0 (rem n 2)))}}}
                    [])
 type-before-predicate (let
                         [calls []]
                         [(cli/parse {count {type <int> validate (fn [n] (lists/append calls n) true)}} ["--count" "wrong"])
                          calls])
 typed (cli/parse {count {type <int> validate (fn [n] (> n 0))}} ["--count" "5"])
 unknown (cli/parse
           {count {validate {<typo>
                             pred :int?}}}
           [])}
=
DUST Result
{bad-message #err {<mismatch type>
                   message "validation message must be a string"}
 bad-predicate #err {<expected function>
                     message "expected a function value"}
 callback-closure {arguments []
                   options {count 5}}
 command {count 4}
 default {arguments []
          options {count 4}}
 false-default {arguments []
                options <!flag>}
 false-message #err {<mismatch type>
                     message "validation message must be a string"}
 missing [{arguments [] options {count null}} []]
 missing-multiple [{arguments [] options {item []}} []]
 multiple {arguments []
           options {item ["Paul" "Chani"]}}
 predicate-error #err {<division integer zero>
                       message "division by zero"}
 rejected #err {<invalid value>
                message "--count: validation failed; got 0"}
 rejected-default #err {<invalid value>
                        message "--count: must be even; got 3"}
 type-before-predicate [#err {<invalid value>
                              message "invalid command-line option value"}
                        []]
 typed {arguments []
        options {count 5}}
 unknown #err {<invalid value>
               message "unknown validation field"}}
DUST
{
case0 (cli/command {name "check" args ["directory" "logs"] <variadic>
              options {count {type <int> short "n" default 3 desc "Repetitions"}}}
             ["-n5" "suite" "one.log" "two.log"])
case1 (cli/command {name "check" args ["input"] options {verbose {type <boolean> short "v"}}}
             ["-v" "file.dust"])
case2 (cli/command {name "check" args ["input"]} ["--" "--help"])
case3 (cli/format-opts {count {type <int> short "n" default 3 desc "Repetitions"}})
case4 (cli/command {name "check" args ["same" "same"]} [])
case5 (cli/command {name "check" args ["input"] options {input {}}} [])
case6 (cli/command {name "check" <variadic>} [])
case7 (cli/command {name "check" options {help {}}} [])
case8 (cli/command {name "check" options {verbose {short "h"}}} [])
case9 (cli/command {name "check" variadic "yes"} [])
case10 (cli/format-opts {count {desc 42}})
case11 (cli/parse {count {desc "Repetitions" type <int>}} ["--count" "5"])
}
→
Canonical DUST
{case0 (cli/command
         {<variadic>
          args ["directory" "logs"]
          name "check"
          options {count {default 3
                          desc "Repetitions"
                          short "n"
                          type <int>}}}
         ["-n5" "suite" "one.log" "two.log"])
 case1 (cli/command
         {args ["input"] name "check" options {verbose {short "v" type <boolean>}}}
         ["-v" "file.dust"])
 case10 (cli/format-opts {count {desc 42}})
 case11 (cli/parse {count {desc "Repetitions" type <int>}} ["--count" "5"])
 case2 (cli/command {args ["input"] name "check"} ["--" "--help"])
 case3 (cli/format-opts {count {default 3 desc "Repetitions" short "n" type <int>}})
 case4 (cli/command {args ["same" "same"] name "check"} [])
 case5 (cli/command {args ["input"] name "check" options {input {}}} [])
 case6 (cli/command
         {<variadic>
          name "check"}
         [])
 case7 (cli/command {name "check" options {help {}}} [])
 case8 (cli/command {name "check" options {verbose {short "h"}}} [])
 case9 (cli/command {name "check" variadic "yes"} [])}
→
Evaluation cases
#cases [{output {count 5
                 directory "suite"
                 logs ["one.log" "two.log"]}
         select "case0"}
        {output {<verbose>
                 input "file.dust"}
         select "case1"}
        {output {input "--help"}
         select "case2"}
        {output "  -n, --count VALUE  Repetitions (default: 3)\n  -h, --help  Show this help"
         select "case3"}
        {output #err <invalid value>
         select "case4"}
        {output #err <invalid value>
         select "case5"}
        {output #err <invalid value>
         select "case6"}
        {output #err <invalid value>
         select "case7"}
        {output #err <invalid value>
         select "case8"}
        {output #err <mismatch type>
         select "case9"}
        {output #err <mismatch type>
         select "case10"}
        {output {arguments []
                 options {count 5}}
         select "case11"}]

median requires a nonempty list of one numeric kind. An odd median preserves the kind; an even median returns a float. CSV cells may be text, numbers, booleans or null. Use the existing format function for numeric precision. Assertions and processes/exit terminate evaluation even inside ordinary error-handling forms; embedded hosts receive a evaluation error, never OS exit.

DUST
(cli/parse {count {short "n" type <int> default 3}
            verbose {short "v" type <boolean>}}
           ["-vn10" "dune.dust"])
(processes/shell/quote "Paul's book")
(formats/csv/row ["Atreides, Paul" 42 true null])
(stats/median [9 1 5])
(format "%.3f" (stats/median [1.0 2.0]))
(terminals/character-width "é界😀")
(tests/equal 3 (stats/median [5 3 1]))
→
Canonical DUST
(cli/parse
  {count {default 3 short "n" type <int>} verbose {short "v" type <boolean>}}
  ["-vn10" "dune.dust"])
(processes/shell/quote "Paul's book")
(formats/csv/row
  [
    "Atreides, Paul"
    42
    true
    null])
(stats/median [9 1 5])
(format "%.3f" (stats/median [1.0 2.0]))
(terminals/character-width "é界😀")
(tests/equal 3 (stats/median [5 3 1]))
=
DUST Result
{arguments ["dune.dust"]
 options {<verbose>
          count 10}}
"'Paul'\\''s book'"
"""
  "Atreides, Paul",42,true,\r

"""
5
"1.500"
5
true