signal-handler
A signal handler shares a global with the code it interrupts, or calls a function that is not async-signal-safe.
- Group
- Code
- Runs
- On by default
- Level
- warning
- Reads
- Every file
- Fix
- None: what the handler should do instead depends on what the signal means to the program
Why
A function registered with signal or through sigaction runs between any two statements of the program, and a lock cannot keep it apart, since the code it interrupts may hold the lock. A global the handler writes and the program reads, or the handler reads and the program writes, is torn or stale unless it is volatile sig_atomic_t or atomic. A call of a function that is not async-signal-safe, such as printf or malloc, can run while the interrupted code is inside the same function, whose state is then broken. Have the handler only set a volatile sig_atomic_t flag, or call only async-signal-safe functions such as write and _exit.
The fix, as Ur suggests it: set a volatile sig_atomic_t flag and act on it outside the handler.
For agents
In a signal handler, only set a volatile sig_atomic_t flag and call only async-signal-safe functions.
Example
src/server.c#include <signal.h>
#include <stdio.h>
static int running = 1;
static void on_term(int sig) {
printf("stopping\n");
running = 0;
}
int main(void) {
signal(SIGTERM, on_term);
while (running) {
}
return 0;
}
$ ur lint --rule signal-handler
warning[signal-handler]: the signal handler `on_term` calls `printf`, which is not async-signal-safe, and the code it interrupts may be inside `printf` too
--> ./src/server.c:7:5 function `on_term`
= step 1: ./src/server.c:12:5 `on_term` is registered as a signal handler here
= hint: set a `volatile sig_atomic_t` flag and act on it outside the handler
= see: 2.4 Signal Concepts, The Open Group and IEEE, POSIX.1-2024 (IEEE Std 1003.1-2024), System Interfaces (2024-06), https://pubs.opengroup.org/onlinepubs/9799919799/functions/V2_chap02.html#tag_16_04
warning[signal-handler]: the signal handler `on_term` writes `running`, which the code it interrupts also uses, and `running` is not `volatile sig_atomic_t` or atomic
--> ./src/server.c:8:5 function `on_term`
= step 1: ./src/server.c:13:12 `running` is used here, outside the handler
= step 2: ./src/server.c:12:5 `on_term` is registered as a signal handler here
= hint: set a `volatile sig_atomic_t` flag and act on it outside the handler
= see: 2.4 Signal Concepts, The Open Group and IEEE, POSIX.1-2024 (IEEE Std 1003.1-2024), System Interfaces (2024-06), https://pubs.opengroup.org/onlinepubs/9799919799/functions/V2_chap02.html#tag_16_04
0 clone classes and 2 concurrency findings in 1 file
Source
2.4 Signal Concepts, The Open Group and IEEE, POSIX.1-2024 (IEEE Std 1003.1-2024), System Interfaces (2024-06).