CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 2 of 7 · 2 min read

Signals

Think of a doorbell, a fire alarm and a power cut in a building. The doorbell can be ignored or answered at leisure, the fire alarm asks everyone to leave in an orderly way, and the power cut is not a request at all. The analogy stops in one place: a power cut has no sender, and every signal has a sender, the kernel or another process.

In plain words: A signal is a short message sent to a process by the kernel or by another process (Level 1). Each has a number and a default action. A process may catch a signal and run its own handler, ignore it, or leave the default, which for most signals is to end the process. Two signals cannot be caught or ignored: SIGKILL (9) and SIGSTOP (19). The table lists the common ones.

Signal Number Usual sender Default action
SIGHUP 1 The terminal closed End (daemons use it to re-read settings)
SIGINT 2 Ctrl-C End
SIGQUIT 3 Ctrl-backslash End and dump core
SIGKILL 9 kill -9, the out-of-memory killer End at once, cannot be caught
SIGSEGV 11 The kernel, after a bad memory access End and dump core
SIGTERM 15 kill, a service manager's stop End (should be caught for a clean shutdown)
SIGCHLD 17 A child ended Ignored

When a process ends by a signal, the shell reports the exit status as 128 plus the signal number. So Ctrl-C gives 128 + 2 = 130, SIGKILL gives 128 + 9 = 137, and SIGSEGV gives 128 + 11 = 139. A normal return 0 gives 0.

A worked example. In the memory-limit test of Level 11 the program ended with status 137: 137 - 128 = 9, so it was killed by SIGKILL, the out-of-memory killer. A web server in a log with "exit 139" crashed with a bad memory access. A job with "exit 143" (128 + 15) was told to stop with SIGTERM. A reader who knows the rule needs no table.

The key lines. Use SIGTERM first, since it can be caught and gives the program time to clean up, and SIGKILL last, since it gives none.

Signal

A signal is an asynchronous notification sent to a process, identified by a number. A process may catch it with a handler, ignore it, or take the default action. SIGKILL and SIGSTOP can be neither caught nor ignored.

Example: kill -TERM 1234 sends SIGTERM (15) to process 1234.

Check yourself: 1. Which two signals cannot be caught? 2. What is the exit status of a process killed by SIGSEGV? 3. Why try SIGTERM before SIGKILL?