34. Signals and the process
A server is told to re-read its configuration. A shell is told that the user pressed Ctrl-C. A program is asked, by the operating system, to stop. None of these arrives as a function call, and none of them waits for the program to be ready: the host sends a signal, and the program either hears it or does whatever the host does by default. Here is one heard:
use std.signal
fn main() -> !int {
signal.listen(signal.reload())?
signal.raise(signal.reload())?
let heard = signal.wait(signal.reload() | signal.terminate())?
print("heard reload: {heard == signal.reload()}")
0
}
The program says which signal it wants to hear, sends that signal to itself, and parks until one of two arrives. Every line is ordinary code running in ordinary control flow, and that is the whole design. This chapter is about what a wolf program can ask the host about itself: the signals it hears and sends, the ids it runs as, and the terminal it reads from. It also covers what each of those questions costs in a manifest, and which machines decline to answer.
The fences name which machines run each program. With the matching std tree beside both tools, the signal-set validation and mode-conversion examples run on both; importing std is not itself a compiler-only restriction. Calls the interpreter cannot provide remain one-machine examples. A successful exit alone does not make their output equivalent.
34.1 A signal is an event
A signal handler, in C, is a function the host calls in the middle of whatever your program was doing. It may run between any two instructions, and it may call almost nothing: no allocation, no lock, nothing that might be half-way through running already. A program that does real work in a handler is a program with a bug that has not happened yet.
Wolf has no handlers. A program listens for a signal, and the
runtime installs a handler of its own that does one thing: it writes a
byte naming the signal to a pipe. A thread the runtime keeps reads that
pipe and queues what arrived. The program takes deliveries off the queue
with signal.wait, which parks the calling task until one comes, or
signal.poll, which never waits and answers 0 when the queue is empty.
No wolf code ever runs in the handler, because the handler is not yours.
The pipe and the thread are made before main, in any program that
listens or waits, so that no listen has to ask the host for a
descriptor once the program is running. A program started at its
descriptor limit therefore finds out before its first line: it does not
start, standard error gets one line, wolf: the runtime could not make its signal hub (Too many open files (os error 24)); the program did not start, and the exit status is 71, as for the readiness set of §33.3.
So the program above has three steps. signal.listen(signal.reload())
registers interest. Nothing is heard without it, and a program that never
listens carries no signal machinery at all. signal.raise delivers the
signal to this process, which is how a program triggers its own reload
path (and how this page tests one). signal.wait takes a set, here
reload() or terminate(), and answers the one that arrived.
A signal has one of three effects on a process, and the program picks
one per signal: what the host does by default (signal.reset), nothing
at all (signal.ignore), or a delivery the program reads
(signal.listen). The last call for a signal wins. The difference that
matters most is what a child inherits. A child starts with every signal
this program ignores still ignored, and every signal it listens for back
at the default, because the handler does not survive starting another
program. That is why a shell listens for Ctrl-C rather than ignoring it:
the shell survives the interrupt, and the sleep it started still dies
of it.
Twenty-eight names
reload() is a function, and it answers an int. A signal in wolf is
named by what happened, never by the number the host gives it, and
std.signal has a function for every meaning there is:
| name | what happened | POSIX |
|---|---|---|
reload() | re-read configuration | SIGHUP |
terminate() | shut down now | SIGTERM |
quit() | shut down after draining; Ctrl-\ | SIGQUIT |
upgrade() | swap in a new binary | SIGUSR2 |
interrupt() | the terminal’s Ctrl-C | SIGINT |
suspend() | the terminal’s Ctrl-Z | SIGTSTP |
bg_read() | a background group read the terminal | SIGTTIN |
bg_write() | a background group wrote to, or set, the terminal | SIGTTOU |
child() | a child stopped or ended | SIGCHLD |
user() | another program’s own reason | SIGUSR1 |
alarm() | a timer ran out | SIGALRM |
broken_pipe() | a write nobody will read | SIGPIPE |
abort() | the process was asked to abort | SIGABRT |
continued() | the process was continued after a stop | SIGCONT |
resize() | the terminal’s window changed size | SIGWINCH |
urgent() | out-of-band data on a socket | SIGURG |
virtual_alarm() | a user-time timer ran out | SIGVTALRM |
profile_alarm() | a profiling timer ran out | SIGPROF |
cpu_limit() | the CPU-time limit was passed | SIGXCPU |
file_limit() | the file-size limit was passed | SIGXFSZ |
kill() | end now; cannot be caught or ignored | SIGKILL |
stop() | stop now; cannot be caught or ignored | SIGSTOP |
segment_fault() | an invalid memory reference | SIGSEGV |
bus_error() | an access past a memory object | SIGBUS |
arithmetic() | an erroneous arithmetic operation | SIGFPE |
illegal() | an illegal instruction | SIGILL |
breakpoint() | a trace or breakpoint trap | SIGTRAP |
bad_syscall() | a bad system call | SIGSYS |
The first twenty are listenable: every signal POSIX names that a
program may catch. The last eight may only be sent. Nobody can catch
kill() or stop(), and a program that returned from a real fault would
run the faulting instruction again, so the six fault signals are
send-only too. (continued() is spelled that way because continue is a
keyword.)
A set of meanings is their bitwise OR, signal.interrupt() | signal.terminate(), and every call that takes a set holds it to one
rule: an empty set, or a set holding anything that is not a listenable
meaning, is the io row, and nothing changes.
use std.signal
fn listen_row(set: int) -> str {
signal.listen(set) else |e| {
return match e {
io => "io",
}
}
"ok"
}
fn main() {
let stop = signal.interrupt() | signal.terminate() | signal.quit()
print("quit is in the set: {(stop & signal.quit()) != 0}")
print("reload is not: {(stop & signal.reload()) == 0}")
print("a set with kill in it: {listen_row(stop | signal.kill())}")
print("an empty set: {listen_row(0)}")
}
$ wolf run sets.lu
quit is in the set: true
reload is not: true
a set with kill in it: io
an empty set: io
The third line is the rule doing its job. The set holds three meanings a program may hear and one it may not, and the listen refuses the whole set rather than hearing three and dropping one. A listen that quietly dropped what it could not hear would answer ok to a typo and listen for nothing.
Each of those functions answers a bit, and the bits are permanent: a
meaning a release has published keeps its bit forever, and a new meaning
only ever takes a bit no release has used. A set a program wrote to a
file means the same thing to every later release. That permanence is a
promise about the table, not an invitation to write the numbers. The
name is the spelling: a program that writes signal.quit() says what it
means on every host, and a program that writes a bit says nothing a
reader can check.
Exercise 34-1 (extension · wolf). Listen for terminate() and
quit() together, raise quit(), and print which of the two the wait
answered. Then poll the same set and print what the poll answers. Predict
the second line before you run it.
34.2 Sending, numbering, and what was ignored
signal.send(pid, meaning) sends a signal to any process by its id, and
it is the one call in this chapter that reaches outside the program. The
meaning may be any of the twenty-eight, kill() and stop() included,
or 0, which sends nothing and answers the same rows: is there such a
process, and may I signal it. The rows are decided in a fixed order. A
pid that is not above 0, or a meaning that is neither 0 nor exactly one
of the table, is invalid, and nothing is sent. A host with no such call
(Windows) is unsupported. Then the target answers: not_found when no
process holds that id, denied when this process may not signal it, and
io for anything else.
use std.signal
use std.env
fn send_row(pid: int, meaning: int) -> str {
signal.send(pid, meaning) else |e| {
return match e {
unsupported => "unsupported",
invalid => "invalid",
not_found => "not_found",
denied => "denied",
io => "io",
}
}
"ok"
}
fn main() -> !int {
print("this process, nothing sent: {send_row(env.pid(), 0)}")
print("two meanings at once: {send_row(env.pid(), signal.user() | signal.alarm())}")
print("an id nobody holds: {send_row(2147483647, 0)}")
print("user has a number here: {signal.number(signal.user())? > 0}")
signal.ignore(signal.user())?
print("user ignored: {(signal.ignored()? & signal.user()) != 0}")
signal.reset(signal.user())?
print("after reset: {(signal.ignored()? & signal.user()) != 0}")
0
}
$ wolf run rows.lu
this process, nothing sent: ok
two meanings at once: invalid
an id nobody holds: not_found
user has a number here: true
user ignored: true
after reset: false
A process id names whichever process holds it at the moment of the call.
A child that has already been reaped may have passed its id on, so a
program that started a child signals it through the child’s handle
(std.process.kill), which has no such hazard, and keeps
signal.send for the processes it did not start: a pid file’s, or its
parent’s.
signal.number(meaning) is the one way from a meaning to the number the
host gives it. The numbers differ between hosts (user() is one number
on Linux and another on macOS), which is why the program above prints
only that there is one. A program needs the number in exactly three
places: printing a signal’s number for a person, as kill -l does;
reading one a person wrote, as trap does; and decoding a shell’s
128 + N exit status. Everywhere else, the name is the interface.
signal.ignored() answers the set of listenable meanings this process
ignores now, and changes nothing. Read before the program’s own first
ignore, reset or listen, it is what the process was started
ignoring, which is how nohup works: nohup starts a program with
reload() ignored, and a program that checks
signal.ignored()? & signal.reload() at start knows it was asked to
survive its terminal going away.
The interpreter declines the two calls that would need the host’s own
signal machinery, by name. Underneath, signal.send is the builtin
os_signal_send, in the prelude like every builtin, and this program
calls it directly:
fn main() -> !int {
os_signal_send(os_pid(), 0)?
print("this process may be signalled")
0
}
$ lupin alive.lu
alive.lu: unsupported: `os_signal_send` signals a process by id: this machine admits no `unsafe` and std has no `kill(pid, sig)` ([os.signal.send], [os.term.note] R8)
lupin is written without unsafe and links no C library, so it has no
way to ask the host to signal a process, or to read a signal’s
disposition, and it says so with the call’s name rather than pretending.
It answers os_pid, os_ppid and os_signal_number itself.
Exercise 34-2 (comprehension · prose). signal.send(pid, 0) sends
nothing. Name two questions a program answers with it, and say why its
rows are decided in the order they are: the shape first, then the host,
then the target.
34.3 Who this process is, and its terminal
env.pid() is this process’s id, a shell’s $$, and what a pid file
holds. It cannot fail, because every host has one. env.ppid() is its
parent’s id now: a process whose parent has ended answers the id of
whatever adopted it, so a program that wants the parent it was started by
reads it once, at start.
The ids a process runs as are four numbers and a list, and std.env
reads them: env.uid() and env.euid() are the real and effective user
ids, and env.gid() and env.egid() the group ids, each int ! {unsupported}. Each is a builtin underneath, the same name with os_
in front (os_uid() and so on, in the prelude). The real id is who
started the process. The effective id
is the one the host checks when the process opens a file, signals another
process or changes an owner, so “am I the super-user?” is env.euid()? == 0. The two differ only in a program started set-user-id.
env.groups() is the supplementary groups, exactly as the host lists
them; whether the effective group is in that list is the host’s choice
(Linux lists it only if the list was set so, macOS puts it first), so a
program that wants every group it is in takes env.egid() and then the
list, and drops a repeat.
use std.env
fn main() -> !int {
print("an id: {env.pid() > 0}, a parent: {env.ppid()? > 0}")
print("started set-user-id: {env.uid()? != env.euid()?}")
print("started set-group-id: {env.gid()? != env.egid()?}")
0
}
$ wolf run who.lu
an id: true, a parent: true
started set-user-id: false
started set-group-id: false
Two more calls change things, and this book does not run either on your
machine. fs.set_owner(path, uid, gid) changes a file’s owner
(fs.set_link_owner a link’s own, fs.set_file_owner an open file’s;
fs.owner_keep() leaves an id as it is), over the builtins
fs_set_owner and fs_set_owner_fd; the host clears a file’s set-user-id and set-group-id bits
when its owner changes, so set the owner first and the mode after.
process.set_ids(uid, gid, groups), over the builtin os_set_ids,
makes this process another user for good: the real, effective and saved ids, and exactly the groups given.
It changes the groups first, then the group ids, then the user ids,
because once the user ids belong to someone else the process may no
longer change a group, and the other order leaves it running as the new
user with the old groups. It returns with every id as asked or every id
as it was. If it cannot put the old ids back after a failure, it ends the
process, with one line on standard error, rather than hand the program a
process that is partly someone else. It is what su and login do, and
what a server does after it binds a low port. Linux serves it; macOS
answers unsupported, because it has no way to read a drop back. Both
calls need the super-user to do anything interesting, which is why no
program here calls them.
The terminal
A terminal has a mode, and std.term reads and sets it as a struct.
canonical is input a line at a time, with the terminal’s own editing;
echo and signals (Ctrl-C, Ctrl-\ and Ctrl-Z become signals) are what
they say; flow is Ctrl-S and Ctrl-Q pausing and resuming output (and
never reaching the program); extended is the host’s extra input
processing, which keeps Ctrl-V and Ctrl-O from the program on macOS even
with canonical off; min and time are how a read waits when input is
not canonical. Under the struct is one int, which the builtins
os_term_mode(fd) and os_term_set_mode(fd, mode) read and write, and
it holds the struct’s three remaining switches too. raw_cr is bit 5
(32): true passes a typed Enter as a carriage return, 13, while false
keeps the terminal’s conversion to a newline. raw_output is bit 6
(64): true passes a written newline alone, while false keeps the
terminal’s output processing, including its added carriage return.
strip8 is bit 7 (128): true strips input to seven bits, while false
keeps the eighth. The literal below sets all three false, the usual
settings. Every other setting is left as it is found, so a mode read
and set back restores exactly what was changed.
use std.term
fn main() {
let cooked = term.Mode {
canonical: true, echo: true, signals: true,
flow: true, extended: true,
raw_cr: false, raw_output: false, strip8: false,
min: 1, time: 0,
}
let raw = term.raw(cooked)
print("canonical {raw.canonical}, echo {raw.echo}, signals {raw.signals}")
print("flow {raw.flow}, extended {raw.extended}, min {raw.min}")
print("round trip: {term.pack(term.unpack(term.pack(raw))) == term.pack(raw)}")
}
$ wolf run modes.lu
canonical false, echo false, signals true
flow false, extended false, min 1
round trip: true
term.raw is the mode a line editor wants: a key at a time, no echo, no
flow control and no extended input, so every key reaches the program, and
signals kept so that Ctrl-C still interrupts. A Mode built by hand
says what it wants of each switch. term.raw preserves raw_cr,
raw_output and strip8 from its argument. The separate raw_bytes
sets the first two true and the third false, passing bytes untranslated
in both directions. Leaving flow and extended
out of a mode is not leaving them alone: it turns them off.
Nothing restores the mode at exit unless the program asks. Save it,
change it and put it back; or hand the saved int to
os_term_restore_at_exit(fd, mode, bytes), and the runtime itself sets
that mode on that terminal and writes those bytes to it (an editor’s
sequence that leaves the alternate screen, say) at every exit it owns: a
return from main, os_exit, an error returned from main, a trap
after its report, a stack overflow’s report, os_exit_signal, and the
death of the proc root. It runs in the runtime, never in a handler of
yours. A death by a signal nobody listened for runs no code at all, the
runtime’s included, so a program that wants its terminal back after a
terminate() listens for it and leaves through os_exit. A process
holds one registration, and the last one wins; a child made by a fork
(§34.7) restores nothing. The rows are invalid for a mode outside the
bits, unsupported on Windows, and io for a handle that is not a
terminal.
Three more terminal questions take the terminal as an fs.File.
term.size(tty) answers the window’s rows and columns, 0 for a size
nobody told the terminal; when the window changes, the foreground group
is sent resize(). term.chars(tty) answers the twelve special
characters the user chose, as named fields (erase, kill,
interrupt, quit, suspend, end_of_file, word_erase,
literal_next, start, stop, reprint, discard), and
term.char_disabled() for one that is turned off, so an editor that
turns canonical and signals off can keep the keys its user set.
signal.wait_fd(tty, set) is the one wait a key and a signal both end:
it answers the meaning that arrived, or 0 when the terminal has something
to read, and reads nothing. Underneath are os_term_size(fd),
os_term_chars(fd) and os_signal_wait_fd(fd, set), which take the
descriptor’s number.
use std.term
use std.fs
fn size_row(tty: fs.File) -> str {
let size = term.size(tty) else |e| {
return match e {
io => "io",
unsupported => "unsupported",
}
}
"{size.rows} rows, {size.columns} columns"
}
fn keys_row(tty: fs.File) -> str {
let keys = term.chars(tty) else |e| {
return match e {
io => "io",
unsupported => "unsupported",
}
}
"interrupt is byte {keys.interrupt}"
}
fn main() {
print("size: {size_row(fs.stdout())}, keys: {keys_row(fs.stdout())}")
}
Run the way this book’s CI runs it, with standard output a pipe, it
prints size: io, keys: io: a pipe is not a terminal, and both calls
answer io. Run it in a terminal and it prints the window’s size and
the byte your Ctrl-C sends.
Exercise 34-3 (comprehension · prose). A program builds a Mode
with canonical, echo and signals set and nothing else, sets it, and
exits. Afterwards its user finds that Ctrl-S no longer pauses a long
listing, and that Ctrl-W no longer erases a word at a cat prompt. Say
which two fields did it, and what the program should have done instead
of building the mode by hand.
34.4 What a call charges, and where it is refused
A package declares the capabilities it reaches (chapter 24), and every call in this chapter is charged to one, or to none:
| charges | builtins | in std |
|---|---|---|
exec | os_signal_listen, os_signal_wait, os_signal_poll, os_signal_raise, os_signal_ignore, os_signal_default, os_signal_send, os_signal_wait_fd, os_set_ids, os_signal_send_group, os_signal_send_all, os_set_pgid, os_wait_poll, os_signal_ignore_one, os_signal_default_one, os_exit_signal, os_wait_status_core, os_wait_poll_core, os_fork, os_signal_wait_fds | signal.listen, wait, poll, raise, ignore, reset, send, send_group, send_all, wait_fd, ignore_one, reset_one; process.set_ids, poll, lead_group, join_group, exit_signal, wait_status_core, poll_core |
env | os_pid, os_ppid, os_signal_ignored, os_uid, os_euid, os_gid, os_egid, os_groups, os_pgid | env.pid, ppid, uid, euid, gid, egid, groups; signal.ignored; term.group; process.own_group |
fs | fs_set_owner, fs_set_owner_fd, fs_sync, fs_sync_dir, fs_realpath | fs.set_owner, set_link_owner, set_file_owner |
| nothing | os_signal_number, os_term_mode, os_term_set_mode, os_term_foreground, os_term_size, os_term_chars, os_signal_last, os_signal_realtime, os_signal_text, os_term_restore_at_exit, os_clock_ns | signal.number, last, realtime, text; term.mode, set_mode, foreground, size, chars |
The reasoning is one rule applied three ways. Changing what a signal
does, waiting for one, sending one (to a process, a group or every
process), ending this process by one, moving into a group, reaping a
child, forking and becoming another user are process control, and process control is exec, with spawning a
child. Reading
this process’s ids and what it ignores is reading its context, which is
env, with the working directory. Changing a file’s owner, syncing a
file or a directory and resolving a path are fs. The
terminal calls act on a descriptor the program already holds and start
nothing, so they carry no capability, as printing does not; a
signal’s host number is a fact about the host’s numbering, like an error
code’s text, as are its last number, its real-time range and its
words; and the clock costs nothing, as time_now_ms does. Every one of
these calls is refused at compile time,
including the free ones: the compiling machine’s ids, terminal,
numbering and clock are not the running machine’s.
What your machine does
Two machines answer fewer of these calls, and both say so by name.
The interpreter has no unsafe and no C library. It answers os_pid,
os_ppid and os_signal_number, and it changes a file’s owner. It does
not hear signals at all: os_signal_listen, os_signal_wait and
os_signal_raise answer their shape rows and decline a well-formed call
by name, and a poll of a well-formed set answers 0, because nothing was
ever heard. It
declines os_signal_ignore and os_signal_default, os_signal_send and
os_signal_ignored, the four id reads, os_groups, os_set_ids and the
three terminal calls above, each by name, as §34.2 showed, after the
call’s shape rows (an empty set is io there too). It answers the shape
rows of §34.5’s group calls, host numbers and words and declines each
well-formed call by name, signal 0’s words included, and it answers
§34.5’s poll with (-1, 0) while it has started no child, declining it
by name once one is live. It answers the shape rows of §34.6’s
one-meaning dispositions and end by a signal and declines a well-formed
call by name, and it answers the core siblings of the wait and the poll
as the compiled machines do. It refuses §34.3’s restore, §34.7’s
fork and §34.8’s wait over descriptors by name after their shape rows.
It serves §34.8’s syncs, canonical paths inside its working tree and
nanosecond clock.
The interpreter’s own archive carries no std tree. When the tools are
in separate directories, stage the compiler’s matching tree beside the
interpreter too, as the samples job does. The set and mode examples then
run on both machines; their output is asserted. Other restrictions above
are restrictions of the calls themselves, not a missing std root.
Windows has no signals as Unix has them, no user or group ids of this
kind, and no terminal calls. A console delivers terminate() for Ctrl-C
and the close button, and quit() for Ctrl-Break, and a program’s own
raise reaches its own listener for any of the first four meanings.
Every other listen is io there. signal.send, signal.number,
signal.ignored, signal.ignore, signal.reset, env.ppid, the id
reads and every terminal call are unsupported once their arguments
have passed the shape rule, and so are §34.5’s group calls, host numbers
and words, §34.6’s one-meaning dispositions and end by a signal, §34.3’s
restore, §34.7’s fork, and of §34.8’s calls the wait over several
descriptors and the directory’s sync.
env.pid answers, and the poll of the children reports a child’s end
and never a stop or a core, because a Windows process cannot be stopped
and leaves no core.
Exercise 34-4 (comprehension · prose). A package’s manifest
declares env and nothing else, and its own code calls os_pid,
os_term_size and os_signal_send. Which of the three fails the build,
and which word would the manifest need for it? Say why it is that word
and not env.
34.5 Groups, and what the children did
A shell runs a pipeline as a job, and it puts every process of the
job in one process group, so that one signal reaches all of them:
Ctrl-C at the terminal interrupts the whole pipeline, not its first
command, and a shell’s kill %1 reaches the job and every child its
commands started. std.process names a group as a process.Group,
whose id is the host’s number for it: process.own_group() is this
process’s, and process.group_of(child) is the group a child leads.
signal.send_group(g, meaning) sends a meaning to every member of the
group this process may signal, and answers signal.send’s rows in
signal.send’s order: the shape, then the host, then the target. The
group’s id must be above 1. Group 1 cannot be named, because the host’s
own spelling of “every process” is the same number with a sign, and a
group id computed wrong must never become a broadcast; the broadcast is
a call of its own, signal.send_all(meaning), which reaches every
process the host lets this one signal. A shell’s kill 0 is
signal.send_group(process.own_group()?, meaning), and it reaches the
caller too.
process.lead_group() makes this process lead a new group of its
own, which is what an interactive shell does at start and what timeout
does before it runs its command, so that a send to its own group reaches
everything the command started. process.join_group(g) moves it into
another group of its session, which is how a shell goes back to the
group it was started in. Both move the caller and nothing else: a
child’s group is chosen when the child is started. A session leader may
not move, and that is denied. Underneath are the builtins
os_signal_send_group, os_signal_send_all, os_set_pgid and
os_pgid, in the prelude.
A program that means to signal its own group leads one first, so that the group holds nothing it did not start:
use std.signal
use std.process
use std.env
fn group_row(g: process.Group, meaning: int) -> str {
signal.send_group(g, meaning) else |e| {
return match e {
unsupported => "unsupported",
invalid => "invalid",
not_found => "not_found",
denied => "denied",
io => "io",
}
}
"ok"
}
fn main() -> !int {
process.lead_group()?
let mine = process.own_group()?
let one = process.Group { id: 1 }
let nobody = process.Group { id: 2147483647 }
print("leads a group of its own: {mine.id == env.pid()}")
print("its own group, nothing sent: {group_row(mine, 0)}")
print("group 1: {group_row(one, 0)}")
print("a group nobody leads: {group_row(nobody, 0)}")
print("two meanings at once: {group_row(mine, signal.user() | signal.alarm())}")
print("host numbers past the table's: {signal.last()? > 28}")
0
}
$ wolf run groups.lu
leads a group of its own: true
its own group, nothing sent: ok
group 1: invalid
a group nobody leads: not_found
two meanings at once: invalid
host numbers past the table's: true
Meaning 0 sends nothing here either, so the second line is the question
kill -0 asks of a group: is there one, and may I signal it.
A host has signals the table of §34.1 has no name for, the real-time
ones above all. The sending calls take signal.host(n) for the host’s
signal n, from 1 to signal.last() (it is -n, the spelling the
builtins take), and signal.realtime() answers the host’s real-time
range as a signal.Realtime, its first and last. A host number
carries no promise past the host that gave it, which is why it gets no
name and no bit: it is how a program sends back a signal it was told
about, as kill -l and a shell’s trap read and print them.
signal.text(meaning) is the C library’s words for a signal, read in
the C locale whatever the user’s language is, and they are the C
library’s own: Killed under one, Killed: 9 under another. Signal 0,
the meaning that sends nothing, has words too (Unknown signal 0, from
glibc), so a table of every signal’s words has no empty row.
The children’s changes
A program that starts children has to find out when one of them changes.
process.poll() never waits. It looks at every child this program
started and has not yet seen end, and answers a process.Change: for
the first child that ended or stopped since it last looked, changed is
true, child is that child and status says what happened; with
nothing to report, changed is false and live is the number of
children still alive, so a live of 0 is “none left”. A
process.Status is one of three kinds that never meet, and its
accessors keep them apart: an exit (process.is_exited, and its
exit_code), an end by a host signal (is_signalled, and signal_of,
the signal’s number), and a stop by one (is_stopped, and
stopped_by: stop() or a terminal’s suspend(), bg_read() or
bg_write()). A child that ended is reaped and its handle closed. A
child that stopped stays, and its stop is reported once. A continue is
not reported at all: whoever sent it knows.
Underneath is the builtin os_wait_poll(), which answers the same
thing as two numbers, (h, status): 0 to 255 for an exit, -N for an
end by host signal N, 256 + N for a stop by it, and (-1, n) with
nothing to report:
fn main() -> !int {
let (h, live) = os_wait_poll()?
print("nothing to report: {h}, {live} live")
0
}
That one runs on both machines, because with no child to ask about the answer needs no host at all. Here is a child that stops and then ends:
use std.signal
use std.process
fn changed(kid: process.Child) -> process.Status ! {io} {
var c = process.poll()?
while !c.changed || c.child.slot != kid.slot {
let _ = signal.wait(signal.child())?
c = process.poll()?
}
c.status
}
fn main() -> !int {
signal.listen(signal.child())?
var cmd = process.command("sleep")
process.push_arg(mut cmd, "10")
var kid = process.start(cmd)?
signal.send(process.pid(kid)?, signal.stop())?
let stopped = changed(kid)?
let stop_n = process.stopped_by(stopped) else 0
print("a stop: {process.is_stopped(stopped)}, by stop(): {stop_n == signal.number(signal.stop())?}")
process.kill(mut kid)?
let ended = changed(kid)?
let end_n = process.signal_of(ended) else 0
print("an end: {process.is_signalled(ended)}, by kill(): {end_n == signal.number(signal.kill())?}")
let after = process.poll()?
print("then: changed {after.changed}, {after.live} live")
0
}
$ wolf run jobs.lu
a stop: true, by stop(): true
an end: true, by kill(): true
then: changed false, 0 live
changed is the whole of a shell’s wait. It polls, and when the poll
has nothing to say it parks in signal.wait until child() arrives,
which the host sends for a stop and for an end. A child() that arrives
between the poll and the wait is already on the queue when the wait
looks, so none is lost, and a program parked there costs nothing while
nothing happens. A shell that also traps a signal adds that meaning to
the listen and the wait, so a wait cut short by the trap and a wait
ended by a child are the same loop. The poll asks the host about each
child the program started, one at a time, and never asks for “any
child”: a child somebody else started is never reaped by mistake. The
stop goes to the child’s id, which no other process can hold while the
child is unreaped, and the end through its handle (process.kill). A
shell prints a stopped job’s status as 128 + N, as for an end, and
process.shell_code(status) is that number for either.
34.6 One signal at a time, and an end by one
signal.ignore and signal.reset take a set, and a set holds only the
twenty listenable meanings. A program sometimes has to choose for a
signal outside them. GNU timeout -s SEGV leads a group, ignores the
signal it is about to send that group, sends it, and lives; and a
wrapper whose command died of a signal has to end by the same one, so
that whoever started the wrapper reads the same end. Five calls in
std.signal and std.process do what a set cannot.
signal.ignore_one(meaning) sets one meaning’s signal ignored, and
signal.reset_one(meaning) sets it back to what the host does by
default. The meaning is the sending calls’: one meaning of the table,
the send-only ones included, or a host number signal.host(n). The rows
are decided in signal.send‘s order: invalid for 0, for anything the
sending calls refuse, and for kill() and stop(), which nothing can
catch or ignore; unsupported on Windows; then io where the host
refuses a number (the C library keeps some real-time numbers for
itself). For one of the twenty listenable meanings the call is the set
calls’ own, and it ends a listen as they do.
use std.signal
use std.env
fn one_row(meaning: int) -> str {
signal.ignore_one(meaning) else |e| {
return match e {
invalid => "invalid",
io => "io",
unsupported => "unsupported",
}
}
"ok"
}
fn main() -> !int {
print("kill: {one_row(signal.kill())}, stop: {one_row(signal.stop())}")
print("nothing: {one_row(0)}, two at once: {one_row(signal.user() | signal.alarm())}")
print("a fault meaning: {one_row(signal.segment_fault())}")
signal.send(env.pid(), signal.segment_fault())?
print("lived through the segment_fault() it sent itself")
signal.reset_one(signal.segment_fault())?
0
}
$ wolf run one.lu
kill: invalid, stop: invalid
nothing: invalid, two at once: invalid
a fault meaning: ok
lived through the segment_fault() it sent itself
The last two lines are the runtime keeping a rule. segment_fault() and
bus_error() are the runtime’s own: it watches for them to catch a task
that runs off the end of its stack, and it tells a signal a process
sent from a real fault. A sent one does what the program chose, which
is the host’s default (the program dies of it) until the program chooses
otherwise, and nothing at all under an ignore. A real fault is the
runtime’s whatever the program chose: a stack overflow is still its
report and exit 134, and any other real fault the host’s default,
because a program that returned from one would run the faulting
instruction again. macOS describes a sent fault the way it describes a
real one, so there the runtime can tell only a fault this program sent
itself, as one.lu does; one sent by another process ends the program
under the default, and under an ignore is lived through once.
process.exit_signal(meaning) ends this process by a signal, in the same
shape, so that its parent reads the end as an end by that signal and a
shell reports 128 + N. It sets the signal back to the default, lets
the calling thread take it, and raises it there. A process that lives on
anyway (a meaning whose default does nothing, such as child()) exits
with 128 + N, so the call never returns for a meaning in its shape: it
answers only invalid, and unsupported on Windows.
A wrapper that says how its command ended also wants to know whether the
command left a core, as timeout prints “(core dumped)”.
process.wait_status_core(take child) waits for a child and reaps it.
Its answer includes a core: a child that dumped one ends as
-(256 + N), below every end without one. process.wait_status answers
-N whether or not a core was written, so a program that compares its
answer with -N reads what it always read. Which ends write a core is
the host’s business, and some hosts write one whatever ulimit -c
says. Either way the status’s low byte, |status| & 255, is N, and a
shell’s exit status for the end, (128 - status) & 255, is 128 + N.
process.poll_core() polls without waiting. It returns a CoreChange:
change is the Change that process.poll returns, with a signal
status normalized to -N, and core says whether the host wrote a
core. When nothing changed, change.changed is false, change.live
counts the live children, and core is false. A program uses
the wait or the poll for an end, not both: the call that reports it
reaps the child.
Here is a program that ends by terminate(), read by a parent that is
the same program, re-executed with a marker argument as chapter 33’s
prefork server is:
use std.signal
use std.process
use std.env
fn main() -> !int {
for a in env.args() {
if a == "again" { process.exit_signal(signal.terminate())? }
}
var again = process.command(os_exe()?)
process.push_arg(mut again, "again")
let kid = process.start(again)?
let status = process.wait_status_core(take kid)?
let n = signal.number(signal.terminate())?
print("ended by terminate(): {status == 0 - n}")
print("and with a core: {status == 0 - (256 + n)}")
let quiet = process.poll_core()?
print("children left: {quiet.change.live}, core: {quiet.core}")
0
}
$ wolf run again.lu
ended by terminate(): true
and with a core: false
children left: 0, core: false
terminate()’s default writes no core, so the child’s end is -N from
either wait, and the second line is false on every host. The poll finds
no children left after the wait reaps this one.
The compiler’s output is asserted here. With the staged std, lupin 0.1.58
on Linux exits 0 but prints ended by terminate(): false on the first
line, and that is the specified answer: under an interpreter os_exe()
names the interpreter ([os.proc.exe]), so the program starts the
interpreter again rather than itself, and a program that spawns itself
is a compiled program’s example
(wolf-interp#371
closed with that answer).
The example stays compiler-only: exit 0 alone does not establish the
printed signal-status result. Its declared Windows refusal is unchanged.
A shell reads the same end as 128 + N. Build the program and give it
the marker yourself, so that it is the process that ends:
$ wolf build again.lu && ./again again
$ echo $?
143
143 is 128 + 15, and 15 is terminate()’s number on every Unix
(POSIX fixes it for kill -15). Bash and dash also print Terminated on
a line of their own as the program ends: that is the shell talking, not
the program.
34.7 A child that keeps running
os_spawn starts another program. A shell’s subshell, the parentheses
in (cd /tmp && ls), needs something else: a second process that runs
the shell’s own code from where it stands, so that the cd inside the
parentheses changes nothing outside them. That is a fork, and it is
the one call in this chapter that returns twice:
fn main() -> !int {
var count = 1
let (r, w) = os_pipe()?
let (pid, h) = os_fork()?
if pid == 0 {
count += 1
fs_write(w, "answered ({pid}, {h}), its count {count}") else |_| {}
os_exit(3)
}
fs_close(w)?
let said = fs_read(r, 64)?
let status = os_wait_status(h)?
print("the child: {said}")
print("the parent: its count {count}, the child's status {status}")
print("the parent was answered a pid and a handle: {pid > 0 && h >= 0}")
0
}
$ wolf run fork.lu
the child: answered (0, -1), its count 2
the parent: its count 1, the child's status 3
the parent was answered a pid and a handle: true
os_fork() -> (int, int) ! {busy, io, unsupported} makes a child
process that runs on from the call, and the call answers in both
processes. The parent is answered (pid, h): the child’s process id,
and its handle in the table os_spawn fills, so os_wait_status, the
poll of §34.5, os_proc_pid and os_kill serve the child as they serve
a spawned one. The child is answered (0, -1), which is how each copy of
the program learns which one it is. Here the child writes one line into a
pipe made before the fork and ends with os_exit(3); the parent reads
the line, then the status.
The child is a copy of the program at the instant of the call: every
value and region, and the scopes the caller had open. Its count moved
and the parent’s did not. What the two share is what the host holds for
them, the descriptors first: every one is shared, offsets included,
which is how the pipe carried the child’s words back, and why a file
both of them write keeps both writes, neither over the other. The child
keeps the signal dispositions and the mask, with nothing pending. Its process id is its
own and its parent’s is the caller’s; its group, session, working
directory, umask, ids and terminal are the parent’s until it changes
them; and an exec in the child replaces the image under the same id,
which is how a shell runs a command inside a subshell.
The runtime’s own machinery is the child’s own. The child has one
thread, the caller’s. Its signal hub is new, made before the call
returns, because the pipe it inherited is the parent’s and a signal
meant for the child must never land there; a meaning the parent listens
for, the child listens for too, until it says otherwise. Its readiness
set (§33.3) is made at its first parking call and its pool of workers at
its first spawn. Its table of children starts empty: the parent’s
children are not the child’s, and a wait on a handle the parent held is
io there. A shell’s subshell puts back every signal it listened for
with signal.reset and leaves the ignored ones ignored, which is what
POSIX asks of a subshell’s traps.
The fork has one rule of its own, and it is a row:
fn fork_row() -> str {
let (pid, h) = os_fork() else |e| {
return "{e}"
}
if pid == 0 {
os_exit(0)
}
let status = os_wait_status(h) else 1
"a child, its status {status}"
}
fn main() -> !int {
let go = channel[int](0)
scope s {
s.spawn(fn() {
let _ = go.recv() else |_| 0
})
print("a task live: {fork_row()}")
go.send(1)?
}
print("every task joined: {fork_row()}")
0
}
$ wolf run busy.lu
a task live: busy
every task joined: a child, its status 0
A fork answers busy, before the host is asked, while any task is
live anywhere in the program (queued, running, or parked in a wait),
from inside a task or a proc’s handler, and under the deterministic
scheduler of chapter 17. So only main forks, and only with no task
live: join them first, as busy.lu does before its second fork. The reason is
the locks. A task may hold one of the runtime’s locks, the C library’s,
or the standard output’s for as long as it runs, and the child has only
the caller’s thread, so a lock another thread held at the instant would
stay held in the child forever, by a thread that is not there. With no
task live, every thread the runtime made is idle, and the fork brings
each to rest where it holds no lock before it asks the host. io is the
host’s refusal (a process limit, or memory), and nothing is made.
The fork runs on the native and release machines on Linux and macOS.
Windows has no fork and answers unsupported. So does the checked
machine, on every host: it is the wolf process interpreting your
program, and a fork there would copy the compiler. A program that keeps a
way to do its work without a fork takes it there and runs to its end.
The checked machine’s record of busy.lu is that end, both forks
answered unsupported and the program’s exit 0:
$ wolf conform-run --json --checked busy.lu
{"commit":"0261597","diagnostics":[],"file":"./busy.lu","impl":"wolfgang","impl_version":"0.2.41","phase_reached":"run","protocol":1,"seeded":false,"stdout_inline":"a task live: unsupported\nevery task joined: unsupported\n","stdout_sha256":"9d68e8cc173c041e58fd1a7c2b68a4d13173fde1b99316577585f8d80593b2ce","verdict":"exit(0)","warnings":[]}
34.8 What an editor asks of the host
An editor asks more of the host than any other program in this chapter. It puts the terminal in raw mode and has to hand it back however it ends (§34.3). It waits on the keyboard, on its jobs’ output, on its signals and on a timer, all at once. It saves a file so that a crash leaves the old file or the new one under the name, never a mix and never neither. It takes two spellings of one directory for one directory. And it times itself in less than a millisecond. Five builtins, in the prelude, serve the last four.
use std.signal
fn main() -> !int {
signal.listen(signal.resize())?
let (r, w) = os_pipe()?
let start = os_clock_ns()
let (i, m) = os_signal_wait_fds([r], signal.resize(), 25)?
let waited = os_clock_ns() - start
print("nothing came: ({i}, {m}), and 25 ms passed: {waited >= 25000000}")
fs_write(w, "k")?
let (j, n) = os_signal_wait_fds([r], signal.resize(), 0)?
print("a byte waits in the pipe: ({j}, {n})")
signal.raise(signal.resize())?
let (k, p) = os_signal_wait_fds([r], signal.resize(), -1)?
print("a resize beside it comes first: {k == -1 && p == signal.resize()}")
0
}
$ wolf run wait.lu
nothing came: (-1, 0), and 25 ms passed: true
a byte waits in the pipe: (0, 0)
a resize beside it comes first: true
os_signal_wait_fds(fds, set, deadline_ms) is §34.3’s os_signal_wait_fd
with a list of descriptors and a deadline. It parks until a meaning in
set arrives, and answers (-1, m); or until one of fds has
something to read (a byte, the end of the input, a hang-up), and answers
(i, 0) with i the lowest such index in the list, reading nothing; or
until deadline_ms milliseconds pass, and answers (-1, 0). A deadline
of 0 looks once and never parks, and -1 never passes. A meaning and a
ready descriptor together answer the meaning, and the descriptor, still
ready, answers the next wait; among descriptors the earlier one in the
list wins, so a program puts the one it serves first first. That is the
whole of an editor’s loop: one wait over the terminal, its jobs’ pipes
and its signals, with the next timer as the deadline, such as the 25
milliseconds that tell a lone Escape from the start of an escape
sequence. A set the shape rule refuses, an empty one included, is io
(a wait on descriptors alone still listens for something), a deadline
below -1 is invalid, Windows is unsupported, and a closed handle is
io.
os_clock_ns() is the monotonic clock in nanoseconds, the clock
time_now_ms reads and from the same anchor, so its values compare and
subtract and are never dates. It never goes backwards and never fails,
and the program above times its own wait with it. Its reason is the
size of an editor’s budget: a few milliseconds from a key to the screen,
and a tenth of a millisecond of work timed by time_now_ms reads 0
nearly every time.
The save is five calls, and the file and the directory each get a sync:
fn exclusive(path: str) -> str {
let f = fs_open_perm(path, 4, 420) else |e| {
return "{e}"
}
fs_close(f) else |_| {}
"made"
}
fn main() -> !int {
let tmp = "notes.txt.new"
if fs_exists(tmp) {
fs_remove(tmp)?
}
fs_write_text("notes.txt", "old")?
let t = fs_open_perm(tmp, 4, 420)?
fs_write(t, "new")?
fs_sync(t)?
fs_close(t)?
print("the temporary name, made again: {exclusive(tmp)}")
fs_rename(tmp, "notes.txt")?
fs_sync_dir(".")?
let saved = fs_read_text("notes.txt")?
print("saved: {saved}")
fs_create_dir_all("drafts")?
let here = fs_realpath(".")?
let up = fs_realpath("drafts/..")?
print("drafts/.. is this directory: {up == here}")
let gone = fs_realpath("nowhere") else |e| "{e}"
print("a name nothing holds: {gone}")
0
}
$ wolf run save.lu
the temporary name, made again: exists
saved: new
drafts/.. is this directory: true
a name nothing holds: not_found
The temporary file is made in the target’s directory, and made
exclusively: fs_open_perm(path, 4, 420) opens for writing a file
that must not exist yet (open mode 4), with the permission bits 420
(octal 644) from its first instant, and answers exists for a name that
is taken, so two saves never share one. (Windows has no permission bits
and answers unsupported there; fs_open_mode(path, 4) is the same
exclusive open without them.) fs_sync(handle) puts the
file’s bytes and its metadata on the disk: fsync on Linux, and
F_FULLFSYNC on macOS, whose fsync leaves them in the drive’s cache.
fs_rename moves the new file over the old name, which every Unix does
atomically. fs_sync_dir(path) then puts the directory’s entries on
the disk, so that the rename survives a crash as well. A crash between
any two of the five leaves the old file or the new one under the name,
whole: the first sync makes the new bytes durable before a name points
at them, and the second makes the name’s move durable. fs_sync answers
io for a handle it cannot sync, such as a pipe. fs_sync_dir answers
not_found for a missing name, invalid for a name that is not a
directory, denied for a refused search, io for anything else, and
unsupported on Windows, whose directories are not opened as files.
fs_realpath(path) answers the absolute name a path names, every link
followed and every . and .. taken, as realpath(3) resolves it:
drafts/.. is this directory, under any spelling of it. A .. is taken
after the link before it, so l/.. is the parent of the link’s target
and not of l, which a walk that reads one component at a time gets
wrong. An editor keys a workspace by its directory’s canonical name, so
two spellings of one directory open one workspace. A missing name, a
dangling link included, is not_found; a loop of links, a component
that is not a directory, a refused search and a name that is not UTF-8
are io.
The checked machine waits, syncs and resolves on the host as the
compiled machines do, and prints this section’s two programs line for
line. The save runs under the interpreter too. On Windows both
machines end it at fs_open_perm, with the unsupported row.
Exercises
Exercise 34-5 (spelunking · prose). Read [os.signal.set.stable]
in the specification. Say what it promises a program that stores a set
of meanings in a file and reads it back under a later release, and what
it does not promise a program that writes a bit by hand.
Exercise 34-6 (design). A long-running program is started by a
user who means it to survive the terminal closing. Write down the first
three things it does with signals, in order, and say why reading
signal.ignored() has to come before its own first listen.
Exercise 34-7 (extension · wolf). Put all twenty-eight names in a
list. For each, ask the host for its number and try a listen (then reset
what you listened for). Print how many meanings there are, how many the
host numbers, how many a listen takes, and what signal.number answers
for two meanings at once. Print counts, not numbers.