Chapter 10: Signals
Signals provide an asynchronous method for handling events.
Signal names start with SIG prefix. Conditions that generate signals:
- Terminal keys
- Hardware exceptions: division by zero, invalid memory reference (SIGSEGV)
- The kill function can send any signal to another process or process group
- Detection of certain software conditions having occurred, such as producer-consumer scenarios
Signals need to inform the kernel, which then executes the corresponding operations.
When a signal occurs, you can instruct the kernel to handle it in the following ways:
- Ignore (except for SIGKILL and SIGSTOP)
- Catch the signal: notify the kernel to call a user function when a signal occurs
- Execute the system default action, which is termination for most signals
The signal function can be used to register callback functions for corresponding signals (including user-defined ones).
Since the address of the signal catching function is likely meaningless in the new program file being executed, exec changes all previously set signals to be caught to their default actions; other signals remain unchanged.
Child processes inherit their parent process’s signal handling methods because child processes copy the parent’s memory space, so the signal catching function’s address remains meaningful in the child process.
Calling a non-reentrant function in a signal handler results in unpredictable behavior.
When a signal is generated, the kernel typically sets some form of flag in the process table (delivery). The period between generation and delivery is called pending.
Superusers can send signals to any process. For non-superusers, the sender’s real user ID must equal the receiver’s real user ID or effective user ID.
Interrupted System Calls
If a process catches a signal while blocked during execution of a slow system call, the system call is interrupted and does not continue execution, returning with an error instead. For example: A process blocked waiting to read user input, but the user has already left the terminal.
Multiple Signal Handling
Processes can choose to block signal delivery by using a signal mask to prevent the kernel from delivering signals (the signal remains pending until unblocked), thus achieving the purpose of blocking delivery.
Signal Sets
The system provides a data structure that can represent multiple signals: signal sets.
Signal Applications
Used for inter-process synchronization.
abort
Terminates the program abnormally. The signal handler for SIGABRT is required to return and will not return to the caller. The only way not to return is if it calls exit, longjmp, or siglongjmp. abort does not respect the process’s blocking or ignoring of this signal. The handler can perform cleanup work before termination.