Waiting for operating system signals: stopping cleanly on Ctrl+C or SIGTERM, noticing terminal resizes, and controlling which thread receives a signal.
import os.signal
A signal is a short message the operating system sends to a process: Ctrl+C sends SIGINT, kill and container runtimes send SIGTERM, and a terminal sends SIGWINCH when its window changes size. By default most signals end the program on the spot, in the middle of whatever it was writing. The os.signal package lets a program take the signals it cares about as ordinary events and react to them at a safe point in its own code.
The model is the same for every use: block the signals, then wait for them. A blocked signal is not delivered; it waits in a queue until a thread asks for it with WaitSignal, Wait or WaitTimeout. Blocking is per thread, and a new thread copies the mask of the thread that started it, so block in main before you start any thread. Then no worker is interrupted, and the one thread that waits receives the signal.
Sets, masks and snapshots are memory blocks the package allocates for you; free each one with mem.Free when you are done. The package grew out of the terminal library tui, which uses it to redraw when the window is resized.
Signals exist on Linux, Android, macOS and the BSDs. On Windows every function is a safe stub: WinchSupported is false, sets are null and waits return WaitInvalid, so the same program compiles everywhere and can fall back to polling.
Stop cleanly on Ctrl+C or SIGTERM
Put SIGINT and SIGTERM in a set, block it, do the work, then wait. WaitSignal returns the number of the signal that arrived, so the program can save its state and exit on its own terms. The example sends itself SIGTERM with Raise so it finishes by itself; in a real program the signal comes from the keyboard or from kill.
os-signal-guide-shutdown.salam
import mem
import os.signal
funcmain:
stop := signal.NewSet()
defer mem.Free(stop)
_ := signal.AddSignal(stop, signal.SigInt)
_ := signal.AddSignal(stop, signal.SigTerm)
ifnot signal.Block(stop):
println"could not block the stop signals"ret1endprintln"working; press Ctrl+C or run kill to stop"
_ := signal.Raise(signal.SigTerm)
sig := signal.WaitSignal(stop)
if sig == signal.SigInt:
println"Ctrl+C: saving and leaving"else sig == signal.SigTerm:
println"SIGTERM: saving and leaving"else:
println"wait failed with status", sig
ret1endret0end
Output
working; press Ctrl+C or run kill to stop
SIGTERM: saving and leaving
Workers keep running, one thread waits
Block first, then start the threads: they inherit the mask, so a signal never lands in the middle of a worker. main waits for the signal and then tells the workers to stop through an atomic flag (see atomic), and joins them.
main got signal 15
worker saw the stop request
clean exit
Notice a terminal resize
SIGWINCH is ignored by default, and on macOS an ignored signal is thrown away even when it is blocked. InstallWinchHandler therefore installs a handler that does nothing, and blocks the signal, so resizes queue up. WaitTimeout waits with a limit, which lets a loop check other things between resizes. Hand the value it returned back to Restore at the end. A signal only says that the size may have changed, and several resizes can arrive as one, so read the new size with term.Size() after every wake-up.
os-signal-guide-resize.salam
import mem
import os.signal
funcmain:
ifnot signal.WinchSupported():
println"no SIGWINCH here: poll term.Size() instead"ret0end
prev := signal.InstallWinchHandler()
if prev == null:
println"could not install the handler"ret1end
set := signal.NewWinchSet()
out := mem.AllocateZeroed(8asu64)
println"nothing yet:", signal.WaitTimeout(set, out, 100) == signal.WaitTimedOut
_ := signal.WakeWinch()
println"after a resize:", signal.WaitTimeout(set, out, 1000) == signal.WaitArrived
println"signal number:", (out asi32*)[0]
mem.Free(out)
mem.Free(set)
println"restored:", signal.Restore(signal.WinchSignal, prev)
mem.Free(prev)
ret0end
Output
nothing yet: true
after a resize: true
signal number: 28
restored: true
Need
Use
Wait for Ctrl+C or SIGTERM
NewSet, AddSignal, Block, WaitSignal
Wait with a time limit
Install, then WaitTimeout
React to terminal resizes
InstallWinchHandler, NewWinchSet, WaitWinch or WaitTimeout
SIGKILL and SIGSTOP can never be blocked, waited for or handled.
•
Only one thread in the process may wait at a time; a second waiter gets WaitBusy instead of half the signals.
•
Signals of one kind do not stack up: two SIGWINCH sent while one is already pending arrive as one.
•
A handler passed to Install runs on whatever thread receives the signal and may only do async-signal-safe work. Blocking and waiting, as above, avoids handlers entirely.
What Wait and WaitTimeout return, and the negative values WaitSignal and WaitWinch return when no signal arrived. WaitArrived is 1, WaitTimedOut is 0, and the failures are negative: WaitInvalid (a bad argument, a missing Install before a timed wait, or Windows), WaitFailed (the system call failed) and WaitBusy (another thread is already waiting).
Gives SIGWINCH a handler that does nothing and blocks it on the calling thread, so resizes queue up for a wait. Returns the previous state: pass it to Restore when you are done, then free it with mem.Free. Null on Windows or when it fails, and then nothing was changed.
Installs handler for sig (null means the default action) and blocks sig on the calling thread. Returns a snapshot of the previous handler and mask: pass it to Restore and then free it with mem.Free. Installing the same handler again only counts one more owner; a different handler for a signal that is already owned is refused with null. The handler runs on whatever thread receives the signal and may only do async-signal-safe work: no allocation, no locks, no printing.
Gives back the state an Install snapshot recorded, on the thread that installed it. While other owners remain, only the owner count drops and the signal stays blocked for them; the last owner puts back the original handler and mask. Restoring again afterwards does nothing and returns true. It does not free the snapshot.
Blocks SIGWINCH on the calling thread so resizes wait in the queue. Threads started afterwards inherit the mask, which lets one watcher thread own the wait. False on Windows or on failure.
Waits until a signal in set is pending, writes its number as an i32 at out[0] and returns WaitArrived. Block the signals first so they queue instead of being delivered. Returns WaitInvalid for a null argument and on Windows, WaitBusy when another thread is already waiting, and WaitFailed when the wait itself failed. Only one thread may wait at a time.
funcWaitTimeout(set: void*, out: void*, millis: int): int
Like Wait, but gives up after millis milliseconds and returns WaitTimedOut; 0 checks once without waiting and a negative value is WaitInvalid. The signal must have been installed with Install first. On macOS the set must hold exactly one signal; Linux takes any set.
Waits for SIGWINCH on a set from NewWinchSet and returns 28 when it arrives, or a negative Wait status. Returns 0 only on Windows, where there is no SIGWINCH.
Adds the signals in set to the calling thread's mask, so they wait in the queue instead of interrupting the thread. Do it before starting other threads so they inherit it. False for a null set, on Windows, or on failure.
Replaces the calling thread's whole mask with set, for example to put back a mask saved with CurrentMask. False for a null set, on Windows, or on failure.
Waits until a signal in set is pending and returns its number, or a negative Wait status when the wait could not run. Block the signals first. This is the simplest way to wait for Ctrl+C or SIGTERM.
Sends sig to this process. When the signal is blocked it only waits in the queue for a Wait. False for a non-positive number, on Windows, or when sending failed.