← Runtimes
Runtimes

Signals, exit status, and termination

Know how a program ended, who finds out, and what cleanup ran.

How a process ends determines its termination report and whether its cleanup path can run.

Outcome

Tell a normal exit from a death by signal, predict which cleanup runs when a program exits or is signaled, and shut down on SIGTERM with cleanup and a meaningful status.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Exit status
A normal exit code; the Linux wait interfaces here expose its low eight bits (0–255). Zero conventionally means success. The complete wait result can also describe termination by signal.
Signal
An asynchronous notification the kernel delivers to a process, such as SIGINT (Ctrl-C), SIGTERM (please stop) or SIGKILL (stop now).
Default action
The action associated with a signal before application handling. On this Linux profile, an unblocked SIGINT or SIGTERM with its default terminating action ends the process without running scope cleanup.
SIGKILL
Signal 9 on Linux. It cannot be caught, blocked or ignored and provides no application cleanup path; sending it does not guarantee a deadline for observing termination.
128 + N
A common reporting convention, including Bash: encode termination by signal N as 128 + N. On Linux this gives 143 for SIGTERM and 137 for SIGKILL; the number alone can also be an explicitly chosen exit code.

Termination and cleanup are separate observations

A process can finish with a normal exit code or be terminated by a signal, an asynchronous notification delivered by the kernel. For these Linux child processes, the completed wait result distinguishes a normal exit code from termination by signal. An ignored or blocked signal need not terminate a process; here SIGTERM has its terminating action.

Cleanup belongs to a control-flow path: returning through an owning scope, unwinding it, calling a process-exit API or receiving a terminating signal need not run the same work. A supervisor’s report describes how the child ended. To establish whether a partial file was removed, also trace the code that owns that cleanup.

01Two ways to end

Exiting and being killed are different endings

An export supervisor reports 143 after a deployment stop, and the next job finds a partial export. Before retrying, you need to know whether the worker chose that code, died from SIGTERM, or returned before removing its temporary file. Keep the termination report and the cleanup result separate as you trace the stop.

Reduce the supervisor to two children: one exits with 7, and the other waits for SIGTERM. Compare the structured results before turning either into a dashboard number.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { spawn } from 'node:child_process';

function start(role: string) {
  const child = spawn(process.execPath, [process.argv[1]!, role], { stdio: 'inherit' });
  return { child, ended: new Promise((resolve) => child.on('exit', (code, signal) => resolve({ code, signal }))) };
}

async function main(): Promise<void> {
  if (process.argv[2] === 'exits') process.exit(7);
  if (process.argv[2] === 'waits') {
    setTimeout(() => {}, 5000);
    return;
  }

  console.log('exited:', JSON.stringify(await start('exits').ended));

  const waiting = start('waits');
  setTimeout(() => waiting.child.kill('SIGTERM'), 200);
  console.log('terminated:', JSON.stringify(await waiting.ended));
}

void main();
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts
The parent sends SIGTERM to the waiting child with its default terminating behavior, then waits for it. What does the second line report?

02Exit skips cleanup

An exit call is not a return

The report now distinguishes the endings, but the partial file still needs an owner. The worker removes it when its cleanup scope finishes. Reduce that scope to a printed marker: a finally block, a deferred call, a value with Drop or a local destructor. Each program prints working, then calls its process-exit function with code 0. Does a successful code prove the scope finished?

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
function exportJob(stop: boolean): void {
  try {
    console.log('working');
    if (stop) process.exit(0);
  } finally {
    console.log('cleanup ran');
  }
}

exportJob(true);
In the recorded runner setup, the function registers cleanup, prints working, then calls its process-exit function with status 0. Which output was observed?

03Handling SIGTERM

A handler should ask, not exit

Returning fixes the worker’s own failure path. A deployment stop arrives from outside that path, so the worker must connect a stop notification to the scope that owns the partial file. With the default terminating action, SIGTERM provides no scope cleanup. A raw C/C++ signal handler can interrupt ordinary code and must obey signal-safety restrictions: a volatile std::sig_atomic_t flag or a permitted lock-free atomic operation can record a request. Node invokes a listener on the event loop; Go can relay a signal into a channel received by ordinary code.

Give the work owner a way to notice the request and leave through its cleanup path. Receiving a notification alone does not stop a loop, and cleaning up alone does not choose a meaningful status. For this supervisor, a handled SIGTERM must finish with code 143. A direct exit from the listener or raw handler bypasses the pending cleanup; _exit and _Exit can be signal-safe while still being wrong for that task.

Receiving SIGTERM with the standard tools
LanguageInstallRuns as
TypeScript (Node)process.on('SIGTERM', listener)An event-loop callback; your loop must yield (await) to see it
Gosignal.Notify(channel, syscall.SIGTERM)A value on a channel, received by ordinary code
RustNo standard API: a crate such as signal-hook, or the C signal functionA raw C handler; the supplied Linux Rust program can record a request with a lock-free atomic
C++std::signal(SIGTERM, handler)A C handler; set a volatile std::sig_atomic_t flag

04Practice

Supervise export jobs

Repair the supervisor report, then the worker’s failure path, then its asynchronous stop path. Each job is a real child of the same program. For signaled jobs, the supplied supervisor waits for the partial file as a readiness marker, sends the requested signal, then reports the wait result and leftover file. This bounded sequential setup isolates cleanup ownership; it does not test every delivery race or crash-recovery policy.

The export supervisor

A supervisor runs export jobs as real child processes and signals some of them. Report how each ended, make a failed export clean up, then stop cleanly on SIGTERM.

  1. easy · R-SIG-V4-1 Read the ending
  2. medium · R-SIG-V4-2 Fail with cleanup
  3. hard · R-SIG-V4-3 Stop on SIGTERM
Check this idea later
A container platform reports that a service “exited with 137”. What most likely happened?
A Go command defers lock.Release() in main and later calls log.Fatal on an error. Is the lock released?
A C++ server installs a SIGTERM handler that calls std::exit(0). On a deploy, temporary files remain. What should the handler do instead?
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.