radlang — System & Process (sys)
This document covers the sys namespace: radlang’s interface to standard I/O,
the process environment, command-line arguments, and timing.
For language fundamentals see the Overview.
Overview
sys is a compiler-intrinsic namespace. Like math and fs, the name is
reserved and dispatched straight to the runtime — it needs no import and
is available everywhere:
fn main() {
sys.output("Hello, radlang")
string name = sys.input("Your name? ")
sys.output("Hi, " + name)
}Everything here is a thin wrapper over the C standard library and POSIX, so it behaves exactly as you would expect from a native program.
Standard output
sys.output(value?) : voidPrints a value followed by a newline. It accepts any type — strings,
numbers, booleans, lists, structs, null, and any — and stringifies it
automatically. Called with no argument it prints a blank line.
sys.write(value) and sys.print(value) print the same way without the newline
(sys.output.write is the same call).
fn main() {
sys.output("plain string")
sys.output(42) // 42
sys.output(3.14) // 3.14
sys.output(true) // true
sys.output([1, 2, 3]) // [1, 2, 3]
sys.output() // (blank line)
}Standard output is buffered unless it is a terminal: a pipe gets the C
library’s buffer, and a regular file (./app > out.txt) gets a 64 KB one, so
large output takes few write calls. Everything written reaches the file when
the program returns from main, calls sys.exit or stops on an uncaught
error. A process killed by a signal (Ctrl-C included) or a crash loses
whatever is still buffered, so write progress you must not lose with
sys.error, which is unbuffered. HTTP access logs already go to stderr.
Standard error
sys.error(message?) : voidSame idea as sys.output, but writes to stderr instead of stdout. Use it
for diagnostics and error messages so they can be redirected separately from
normal program output.
fn main() {
sys.error("warning: config file missing, using defaults")
} Standard input
sys.input(prompt?) : stringReads a line from stdin and returns it as a string (without the trailing
newline). If a prompt is given it is printed first, with no added newline.
fn main() {
string city = sys.input("Where do you live? ")
sys.output("You live in " + city)
}Process control
Exit
sys.exit(code: int) : voidTerminates the process immediately with the given status code (0 means
success). Code after sys.exit in the same path does not run.
fn main() {
if !fs.exists("config.toml") {
sys.error("no config found")
sys.exit(1)
}
sys.output("config OK")
} Environment variables
sys.env(name: string) : string
sys.env(name: string, value: string) : stringsys.env(name)returns the value of an environment variable from the real OS environment, or the empty string if it is not set. It reads only the process environment — it does not see values from your project’sconfig.yamlenv:block. For config-managed values use thecfgnamespace’scfg.env(key)(seecfg.md).sys.env(name, value)sets an environment variable to the specified value in the process environment.
fn main() {
string home = sys.env("HOME")
sys.env("MY_VAR", "my_value")
sys.output("home: " + home)
sys.output("var: " + sys.env("MY_VAR"))
} Command-line arguments
sys.args() : string[]Returns user arguments only. The program/invocation name (argv[0]) is omitted,
so sys.args()[0] is the first argument supplied to the program.
Use sys.executable() to get the absolute path of the running binary.
fn main() {
string[] argv = sys.args()
sys.output("arg count: " + argv.length().toString())
for (string arg in argv) {
sys.output(arg)
}
}Process execution
Running shell commands
sys.cli(cmd: string) : Future<int>Executes a shell command in the background via the worker thread pool. Returns a Future<int> resolving with the process exit code.
async fn listFiles() {
int code = await sys.cli("ls -la")
sys.output("exit code: " + code.toString())
} Spawning subprocesses
sys.spawn(exe: string, args: string[]) : Future<int>Spawns a child process with arguments directly, bypassing the shell. Returns a Future<int> resolving with the process exit code.
async fn runEcho() {
int code = await sys.spawn("echo", ["hello", "world"])
sys.output("exit code: " + code.toString())
} Capturing command output
sys.exec(exe: string, args: string[]) : Future<ProcOutput>Runs an executable directly, captures both output streams, and resolves after
it exits. ProcOutput contains code, stdout, and stderr. Unlike
sys.cli, this bypasses the shell.
async fn render() {
ProcOutput out = await sys.exec("pandoc", ["draft.md", "-t", "html"])
if (out.code != 0) { throw Error(out.stderr, out.code) }
sys.output(out.stdout)
} Managing a long-lived process
sys.start(exe: string, args: string[]) : ProcessStarts an executable immediately and returns a handle. pid() and alive()
are synchronous; wait() resolves with the exit code and output() resolves
with the complete ProcOutput. Use kill() for SIGTERM, or signal(n) for
another signal. Calling kill() or signal() after exit is harmless.
On Unix, subprocess results use the ordinary exit code for normal exits,
128 + signal for signal termination (for example, SIGTERM is 143), and -1
when starting or waiting for the process fails. This convention is shared by
sys.cli, sys.spawn, sys.exec, Process.wait and Process.output.
Process server = sys.start("llama-server", ["--port", "8080"])
// ... use the server ...
server.kill()
int code = await server.wait()On spawn failure, sys.exec and Process.output() resolve with code == -1
and the OS error message in stderr; sys.start still returns a dead handle.
Timing
Blocking sleep
sys.sleep(ms: int) : voidPauses the current thread for ms milliseconds. This blocks everything,
including the async scheduler.
fn main() {
sys.output("waiting one second...")
sys.sleep(1000)
sys.output("done")
} Non-blocking sleep
sys.sleepAsync(ms: int) : Future<void>A cooperative sleep for use with await inside an async fn. Unlike
sys.sleep, it does not stall other pending async tasks — the scheduler is
free to run them while this one waits.
async fn tick() {
await sys.sleepAsync(500)
sys.output("half a second later")
}System information
| Method | Returns | Description |
|---|---|---|
sys.cwd() |
string | Current working directory |
sys.pid() |
int | Process ID |
sys.platform() |
string | "darwin", "linux", "windows", "ios" (iOS builds), "android" (Android builds), or "unknown" |
sys.arch() |
string | "arm64", "x86_64", or "unknown" |
sys.hostname() |
string | The machine’s hostname |
sys.cores() |
int | Number of online logical CPU cores |
sys.home() |
string | The user’s home directory |
sys.tmp() |
string | The system temporary directory |
sys.memory() |
MemoryStats | The process’s memory use (below) |
fn main() {
sys.output("running on " + sys.platform() + "/" + sys.arch())
sys.output("pid " + sys.pid().toString() + " in " + sys.cwd())
sys.output("host: " + sys.hostname())
}Note.
platform()andarch()are resolved at compile time for the target the binary is built for, so they reflect the build host/target rather than being probed at runtime.
Memory use
sys.memory() : MemoryStatsReturns a snapshot of the process’s memory, all fields long:
| Field | Meaning |
|---|---|
residentBytes, residentPeakBytes |
Resident memory now and at its peak (macOS/iOS: physical footprint) |
arenaBytes, arenaPeakBytes |
Young values in the collector’s nurseries (the field keeps its pre-1.39 name) |
arenaOverflowBytes, arenaOverflowPeakBytes |
Legacy; always zero (the traced heap has no arena) |
managedBytes, managedPeakBytes |
Value storage outside the nursery: old values and the heap’s reusable reserve |
transferBytes, transferPeakBytes |
Async and worker results |
connectionBytes, connectionPeakBytes |
Connection, stream and handle memory |
registryBytes, registryPeakBytes |
Registries and configuration |
tempBytes, tempPeakBytes |
Short-lived runtime buffers |
metaBytes, metaPeakBytes |
Runtime bookkeeping |
stackBytes, stackPeakBytes |
Coroutine and signal stacks |
foreignBytes, foreignPeakBytes |
Third-party libraries (not yet accounted) |
totalBytes, totalPeakBytes |
Every class except stacks |
limitBytes |
RADLANG_MEM_LIMIT_MB in bytes, 0 when unlimited |
failures |
Number of out-of-memory failures so far |
fn main() {
MemoryStats before = sys.memory()
int[] xs = []
for (int i = 0; i < 1000000; i++) { xs.add(i) }
MemoryStats after = sys.memory()
sys.output("grew by " + ((after.totalBytes - before.totalBytes) / 1048576).toString() + " MB")
}Running out of memory raises an Error with code 507 (catchable; without a
handler the program prints a report and exits with status 71). The classes,
limits (RADLANG_MEM_LIMIT_MB) and the RADLANG_MEM_REPORT report are
described in Runtime memory.
sys.collect() runs full collections until what is unreachable has been freed. Use
it before a measurement or in a test; the collector does not need it.
Secure storage
Small secrets (API keys, OAuth tokens, passwords) stored by the platform rather than in files the program writes:
| Method | Returns | Description |
|---|---|---|
sys.secureSet(service, key, value) |
bool | Store or replace value; true once saved |
sys.secureGet(service, key) |
string? | The value, or null when there is none |
sys.secureDelete(service, key) |
bool | True when an item was removed, false when there was none |
sys.secureKeys(service) |
string[] | The keys stored under service |
service groups a program’s items (its bundle id or another fixed name) and
key names one item. Both must be non-empty.
fn main() {
string svc = "com.example.notes"
sys.secureSet(svc, "apiKey", "sk-...")
string? key = sys.secureGet(svc, "apiKey")
if key != null { sys.output("have a key") }
sys.secureDelete(svc, "apiKey")
}| Platform | Where items live |
|---|---|
| iOS | Keychain generic passwords, readable after the first unlock, on this device only. Device builds sign in the provisioning profile’s keychain group; simulator builds carry their own. |
| macOS | The login keychain. macOS asks the user before a program reads an item that a different build stored: an unsigned or ad-hoc rebuild counts as different, a build signed with the same identity (build.macos.sign) does not. |
| Android | Each value is encrypted with an AES-256-GCM key kept in the Android Keystore and written under the app’s private files (.rad-secure/). The key never leaves the device, so backups restored elsewhere cannot decrypt them. |
| Linux, other | Not available: every call throws a catchable Error. |
Platform failures (a locked device, a missing entitlement, a refused prompt)
throw a catchable Error naming the call and the platform’s message.
Clipboard, browser and sharing
| Method | Returns | Description |
|---|---|---|
sys.clipboardSet(text) |
bool | Put plain text on the clipboard |
sys.clipboardGet() |
string | The clipboard’s text, or "" |
sys.openUrl(url) |
bool | Open a URL in the system browser or the app that handles it (mailto:, tel:, …) |
sys.browse(url, onClose) |
bool | Open an http(s) page in an in-app browser; onClose: fn(): void runs when the user leaves it |
sys.shareText(text, subject?) |
bool | Show the share sheet for text |
sys.shareFile(path, mime, title?) |
bool | Show the share sheet for a file |
Each returns false when the platform could not do it (a malformed URL, no app for it, a missing file, no window to present from).
fn main() {
NativeWindow win = syn.window("Share", 390, 844)
SynNode root = win.panel({dir: "column", pad: syn.px(16)})
root.button("Copy link", fn() { sys.clipboardSet("https://example.com/") })
root.button("Sign in", fn() {
sys.browse("https://example.com/login", fn() { sys.output("browser closed") })
})
root.button("Share", fn() { sys.shareText("Look at this", "A link") })
syn.run(win)
}| Platform | Behaviour |
|---|---|
| iOS | UIPasteboard; browse presents SFSafariViewController and onClose runs when the user taps Done; the share sheet is UIActivityViewController (a popover on iPad). The subject is not used. |
| Android | ClipboardManager; openUrl and browse start the default browser, and onClose runs when the user comes back to the app; sharing uses the system chooser. Files are offered through the app’s own read-only content provider, so shareFile only shares files under the app’s files or cache directory (relative paths resolve from the working directory, which is the files directory). Android 10+ only lets the app read the clipboard while it has focus: a clipboardGet in main, before the window is shown, returns "". |
| macOS | NSPasteboard; openUrl and browse open the default browser (onClose never runs); sharing shows NSSharingServicePicker over the key window. |
| Linux | openUrl and browse run xdg-open (onClose never runs); the clipboard and sharing are not available ("" / false). |
onClose runs on the UI thread of a syn.window app; a program without a
syn window never runs it. Starting another browse replaces the pending one.
Haptics
| Method | Returns | Description |
|---|---|---|
sys.haptic(kind) |
bool | Play a haptic tap; false for an unknown kind or a platform without haptics |
kind is "light", "medium" or "heavy" (impacts), "selection" (a
selection tick) or "success", "warning" or "error" (notifications).
root.button("Send", fn() { sys.haptic("light") })
root.toggle({label: "Sounds"}, fn(bool on) { sys.haptic("selection") })| Platform | Behaviour |
|---|---|
| iOS | UIImpactFeedbackGenerator (light, medium, heavy), UISelectionFeedbackGenerator and UINotificationFeedbackGenerator. |
| Android | View.performHapticFeedback on the window, which needs no VIBRATE permission: KEYBOARD_TAP, VIRTUAL_KEY, LONG_PRESS, CLOCK_TICK; success and error use CONFIRM / REJECT on Android 11+ and VIRTUAL_KEY / LONG_PRESS before; warning is CONTEXT_CLICK. Whether the device plays them follows the system’s touch-feedback setting. |
| macOS | NSHapticFeedbackManager (a Force Touch trackpad plays it; otherwise nothing happens). |
| Linux | Not available (false). |
| Headless syn | Prints SYN-HAPTIC <kind> and returns true. |
Platform services
| Method | Returns | Description |
|---|---|---|
sys.service(op, argsJson?) |
string | Run a platform operation; the answer is a JSON object |
sys.onService(fn(string event)) |
void | Set the handler for platform events (JSON objects with an "ev" field) |
One bridge for the services a phone app needs beyond the typed calls above:
speech, text to speech, audio, notifications, background time, an HTML sheet,
PDF text, pickers, incoming URLs and files, calendar, reminders, contacts,
images and device facts. An operation takes its arguments as a JSON object and
answers one. Failures answer {"error": "..."}, and an operation the platform
does not have answers {"error": "unavailable"}. sys.service("ops") lists the
ones it has, so an app can test for a feature before it shows it.
Operations that finish later answer {"ok": true, "pending": true} at once and
report through events. Permission prompts, pickers, recognition, synthesis and
playback all work this way. Events are queued from any thread and run through
the sys.onService handler on the UI thread, from syn’s frame loop.
sys.service("service.poll") delivers them in a program without a window. An
event that arrives before a handler is set waits for one. Set the handler in
main before syn.run, so the notification tap or URL that launched the app is
delivered.
type Ev { string? ev, string? id, string? text }
fn main(): void {
NativeWindow win = syn.window("Dictation", 390, 844)
SynNode root = win.panel({dir: "column"})
SynNode heard = root.label("")
sys.onService(fn(string e): void {
Ev ev = json.parse<Ev>(e)
if ((ev.ev ?? "") == "speech.partial" || (ev.ev ?? "") == "speech.final") { heard.setText(ev.text ?? "") }
})
root.button("Listen", fn() {
sys.service("speech.listen", "\{\"id\":\"d1\",\"onDevice\":true\}")
})
syn.run(win)
}Permission prompts need their Info.plist usage strings (build.ios.infoPlist).
Without one, the operation answers {"error": "missing <key> in Info.plist"}
rather than letting the system end the app.
| Operation | Arguments | Answer, then events |
|---|---|---|
ops |
{ops: [...]} |
|
echo |
any | the arguments; then {ev:"echo", args} (for tests) |
service.poll |
{delivered: n}: runs queued events now |
|
net.resolve |
host |
{addresses: [...]} (getaddrinfo) |
fs.space |
path |
{free, total} bytes |
fs.copy |
src, dst, id? |
Copies on its own thread: fs.progress {id, done, total} at most every 200 ms, then fs.copied {id, ok, error?} |
fs.cancel |
id |
Stops a copy; the partial file is removed |
fs.excludeFromBackup |
path, exclude? (true) |
Keeps a file out of iCloud backups (Apple) |
app.paths |
{resources, documents, caches, support, tmp} (Apple) |
|
date.format |
ms?, timeZone?, locale?, format? (ICU pattern) or date?/time? (none, short, medium, long, full) |
{text, timeZone, offsetMinutes} (Apple) |
date.parse |
text, timeZone? |
{ms} for an ISO 8601 date or date-time. A time without a zone is read in timeZone, or the device’s zone. A date alone is midnight. Z and ±hh:mm offsets are accepted (Apple) |
device.locale |
{locale, languages, timeZone, offsetMinutes} |
|
device.memory |
{physical, available, thermal, lowPower}; available is os_proc_available_memory on iOS. Events: device.memoryWarning, device.thermal {state} |
|
tts.voices |
{voices: [{id, name, language, quality}]} |
|
tts.speak |
text, voice?, rate?, id? |
tts.start, then tts.end or tts.cancel {id}; replaces any utterance |
tts.stop |
||
tts.file |
text, path, voice?, rate?, id? |
tts.file {id, ok, path}: a 16-bit PCM WAV |
audio.play |
path, id?, positionMs?, session? |
{durationMs}; then audio.end {id, ok} or audio.error |
audio.pause / audio.resume / audio.seek {positionMs} / audio.state |
{playing, positionMs, durationMs, id} |
|
audio.stop |
||
audio.session |
mode: playback, spoken, record, ambient |
iOS audio session category |
speech.request |
speech.auth {granted} (speech recognition and microphone) |
|
speech.status |
{status} |
|
speech.listen |
id?, locale?, onDevice? (true), partial? (true) |
speech.partial, speech.final {id, text}, speech.level {level}, speech.error {error}, speech.end {id, cancelled} |
speech.stop / speech.cancel |
stop delivers the final transcript; cancel drops it | |
notify.request |
notify.auth {granted} |
|
notify.status |
{status}: authorized, denied, provisional, notDetermined |
|
notify.post |
title, body, payload?, id?, delaySeconds? |
{id}; a tap later gives notify.open {id, payload}, also on a cold start |
notify.cancel |
id |
|
bg.begin |
name? |
{id}; bg.expired {id} when iOS takes the time back |
bg.end |
id |
|
bg.remaining |
{seconds} (-1: not limited) |
|
web.sheet |
html, title? |
A modal web view, closed with web.closed. Its data store is not persistent, network loads are blocked and a CSP is added. Navigation is limited to about:, data: and blob:. Scripts run. |
pdf.text |
path, maxPages? |
{pages, text} with [page N] sections |
pdf.fromHtml |
html, path, id?, paper? (a4, letter) |
pdf.created {id, ok, path, pages}; paginated on iOS, one tall page on macOS |
photos.save |
path, id? |
photos.saved {id, ok, error?}: adds an image to the photo library (add-only access) |
photos.scan |
kind (summary, largest, videos, screenshots), limit? (25), olderThanDays?, id? |
photos.scanned {id, ok, ...}: counts and bytes by type for summary. Otherwise {matched, matchedBytes, items: [{id, type, created, bytes, favorite, durationSeconds?}]}, largest first (screenshots newest first) |
photos.delete |
ids, id? |
photos.deleted {id, deleted, count}: moves items to Recently Deleted after the system’s own confirmation |
image.info |
path |
{width, height, type} |
image.resize |
src, dst, maxDim?, format? (jpeg, png), quality? (85) |
{width, height}; honours EXIF orientation |
pick.documents |
types? (UTType ids, MIME types or extensions), multiple?, id? |
pick.result {id, paths, cancelled}; files are copied into the temporary directory |
pick.photos |
limit?, id? |
pick.result |
pick.camera |
id? |
pick.result (a JPEG); iOS only |
calendar.request / reminders.request |
calendar.auth {kind, granted} |
|
calendar.status / reminders.status |
{status}: fullAccess, writeOnly, denied, restricted, notDetermined |
|
calendar.list |
from?, to? (ms; default the next 7 days), limit? |
{events: [{id, title, start, end, allDay, location, notes, calendar}]} |
calendar.create |
title, start, end?, allDay?, location?, notes? |
{id} |
calendar.delete |
id |
|
reminders.list |
completed?, limit? |
{reminders: [{id, title, due, completed, notes, list}]} |
reminders.create |
title, due?, notes? |
{id} |
reminders.complete |
id, completed? (true) |
|
contacts.request / contacts.status |
contacts.auth {granted} / {status} |
|
contacts.search |
query, limit? (20) |
{contacts: [{id, name, organization, phones, emails}]} |
messages.compose |
to: [...], body |
The Messages sheet; messages.done {result}: sent, cancelled, failed. iOS only |
URLs and files opened in the app arrive as app.openUrl {url} and
app.openFile {path, name}, with the file copied into the temporary directory.
Declare the scheme (CFBundleURLTypes) and document types in infoPlist.
| Platform | Behaviour |
|---|---|
| iOS | Everything above. |
| macOS | Everything except pick.camera, messages.compose and bg.remaining limits. Pickers use NSOpenPanel, web.sheet opens a window, and bg.begin holds an NSProcessInfo activity. Notifications and permission prompts need an app bundle. |
| Android, Linux | The portable operations: ops, echo, service.poll, net.resolve, fs.space, fs.copy, fs.cancel, device.locale and device.memory. |
Workers
sys.worker starts a long-lived worker thread and talks to it with string
messages. Use one to keep heavy work (model inference, large parses, GPU
setup) off the UI thread or off the thread that serves requests.
fn main() {
Worker w = sys.worker(fn(WorkerPort port): void {
while (true) {
string? m = port.receive() // blocks until a message arrives
if (m == null) {
break // null once w.stop() is called
}
port.reply("echo " + m)
}
})
w.onMessage(fn(string reply): void {
sys.output(reply)
w.stop()
})
w.send("hello")
w.join() // echo hello
}| Call | Returns | Description |
|---|---|---|
sys.worker(body) |
Worker | Start a thread running body: fn(WorkerPort): void (or an async fn(WorkerPort)) |
w.send(message) |
void | Queue a string or byte[] for the worker (copied); never blocks; ignored once the worker stopped or exited |
w.onMessage(handler) |
void | handler: fn(string): void runs on the creating thread for each reply |
w.onBytes(handler) |
void | handler: fn(byte[]): void runs for each byte[] reply |
w.onError(handler) |
void | handler: fn(Error): void gets an error that escaped the body |
w.stop() |
void | Ask the worker to stop: receive/poll return null from now on |
w.join() |
void | Wait until the worker has exited and every reply has been delivered |
w.done() |
Future<void> | Resolves when join() would return (at once if it already has) |
w.isRunning() |
bool | True until the body has returned |
port.receive() |
string? | Next message; waits for one; null once stopped |
port.poll() |
string? | Next message, or null at once if there is none (or once stopped) |
port.receiveBytes() / port.pollBytes() |
byte[]? | The same, as bytes |
port.reply(message) |
void | Send a string or byte[] back to the creating thread (copied); never blocks |
port.stopped() |
bool | True once w.stop() was called |
sys.isWorker() |
bool | True on a worker thread |
sys.service(op, json?) |
string | Platform service operation (JSON answer) |
sys.onService(fn(string)) |
void | Platform events handler (UI thread) |
The worker thread. The body runs on its own OS thread with its own memory
arena, coroutine scheduler and reactor, so async/await, sys.sleepAsync
and http.* work inside it, and GPU handles it creates stay on it (see
gpu.md). Parallel list operations (map(fn, n), parallel, …)
work inside a worker too. The body may be an async fn(WorkerPort port); the
worker then runs until that future settles. When the body returns, coroutines
it started but did not await finish first, then the thread exits.
Messages are copied. send and reply copy the string into a queue, and
receive/poll and onMessage hand the receiver its own copy, so no memory
is shared through messages. Messages arrive in the order they were sent. Send
structured data as JSON (json.stringify / json.parse<T>), or binary data as
byte[]. Both kinds share one queue: receive returns a byte[] message as
text and receiveBytes returns a string message’s UTF-8 bytes, so read each
message with the method that matches what was sent. Replies work the same
way: a string reply goes to onMessage and a byte[] reply to onBytes; with
only one of the two handlers set, it gets both kinds (bytes as text, text as
bytes). The body may read
values it captures, but it runs on another thread: do not change captured
variables from the body, and do not change from outside what the body reads
(as with parallel map callbacks).
Waiting in the worker. receive() waits without busy-looping. In the
body’s own code it keeps the worker’s coroutines running while it waits;
called inside an async fn on the worker it suspends only that coroutine.
poll() never waits.
Replies on the creating thread. onMessage and onError run on the thread
that called sys.worker, one at a time and in order:
- In a
syn.windowapp they run from the UI thread’s frame loop, so they may update nodes directly, and the window redraws afterwards. - Elsewhere they run whenever that thread’s scheduler runs: inside
w.join(),sys.blockOn(...), or while anasync fnon that thread is suspended in anawait(for exampleawait sys.sleepAsync(10)in a loop). Synchronous code that never waits does not receive replies until it does.
Replies queued before onMessage is set are delivered once it is. Memory a
handler allocates is reclaimed after it returns unless the handler stores it
somewhere longer-lived.
Stopping. w.stop() only sets a flag and wakes a waiting receive, which
returns null; messages still queued are dropped. A body that never calls
receive/poll should check port.stopped(). The program exits when main
returns, whether or not workers are still running: call w.join() first to
wait for one. join must be called on the thread that created the worker; it
drives that thread’s scheduler (and delivers replies) while it waits, and
inside an async fn it suspends only the caller. await w.done() does the same
as a future (also usable with Future.race, .timeout and .resolve), and
must also come from the creating thread.
Errors. An error thrown out of the body ends the worker. With an onError
handler it is delivered there (after any replies sent before it); without one
it is printed to stderr as radlang: uncaught error in worker: .... Either way
the rest of the program keeps running. An error thrown by an onMessage or
onError handler is printed and the next reply is still delivered.
Worker w = sys.worker(async fn(WorkerPort port): void {
string? url = port.receive()
HttpResponse r = await http.get(url ?? "")
port.reply(r.body)
})
w.onMessage(fn(string body): void { sys.output(body.length()) })
w.onError(fn(Error e): void { sys.error("worker failed: " + e.message) })
w.send("https://example.com/")
w.join()Workers are available on macOS, Linux, iOS and Android.
Quick reference
| Call | Returns | Purpose |
|---|---|---|
sys.output(v?) |
void | Print to stdout with newline |
sys.error(v?) |
void | Print to stderr with newline |
sys.input(p?) |
string | Read a line from stdin |
sys.exit(code) |
void | Terminate the process |
sys.env(name) |
string | Read an OS environment variable |
sys.env(name, val) |
string | Set an OS environment variable |
sys.args() |
string[] | User arguments, excluding program name |
sys.executable() |
string | Absolute path of running binary |
sys.sleep(ms) |
void | Block for ms milliseconds |
sys.sleepAsync(ms) |
Future<void> | Cooperative async sleep |
sys.cwd() |
string | Current working directory |
sys.pid() |
int | Process ID |
sys.platform() |
string | OS name |
sys.arch() |
string | CPU architecture |
sys.hostname() |
string | Machine hostname |
sys.cores() |
int | CPU core count |
sys.home() |
string | Home directory |
sys.tmp() |
string | Temporary directory |
sys.memory() |
MemoryStats | Memory use by class, resident size, limit |
sys.secureSet(s, k, v) |
bool | Store a secret (Keychain / Keystore) |
sys.secureGet(s, k) |
string? | Read a secret |
sys.secureDelete(s, k) |
bool | Remove a secret |
sys.secureKeys(s) |
string[] | List a service’s keys |
sys.clipboardSet(t) / sys.clipboardGet() |
bool / string | Clipboard text |
sys.openUrl(url) |
bool | Open a URL externally |
sys.browse(url, onClose) |
bool | In-app browser |
sys.shareText(t, s?) / sys.shareFile(p, m, t?) |
bool | Share sheet |
sys.haptic(kind) |
bool | Haptic tap (light, medium, heavy, selection, success, warning, error) |
sys.cli(cmd) |
Future<int> | Run shell command in the background |
sys.spawn(exe, args) |
Future<int> | Spawn subprocess directly with arguments |
sys.exec(exe, args) |
Future<ProcOutput> | Run directly and capture output |
sys.start(exe, args) |
Process | Start a managed subprocess |
sys.worker(body) |
Worker | Start a worker thread with message passing |
sys.isWorker() |
bool | True on a worker thread |
Picking the right tool
- Print results a user should see →
sys.output. - Print warnings/errors that shouldn’t mix with output →
sys.error. - Read interactive input →
sys.input. - Read an OS environment variable →
sys.env; read project config →cfg.env(seecfg.md). - Fail a script with a status code →
sys.exit. - Delay in a normal program →
sys.sleep; delay insideasync→sys.sleepAsync.