Misuse of errno in a signal handler
You read errno
after calling an
errno
-setting function in a signal handler
Description
This defect occurs when you call one of these functions in a signal handler:
signal
: You call thesignal
function in a signal handler and then read the value oferrno
.For instance, the signal handler function
handler
callssignal
and then callsperror
, which readserrno
.typedef void (*pfv)(int); void handler(int signum) { pfv old_handler = signal(signum, SIG_DFL); if (old_handler == SIG_ERR) { perror("SIGINT handler"); } }
errno
-setting POSIX® function: You call anerrno
-setting POSIX function in a signal handler but do not restoreerrno
when returning from the signal handler.For instance, the signal handler function
handler
callswaitpid
, which changeserrno
, but does not restoreerrno
before returning.#include <stddef.h> #include <errno.h> #include <sys/wait.h> void handler(int signum) { int rc = waitpid(-1, NULL, WNOHANG); if (ECHILD != errno) { } }
Risk
In each case that the checker flags, you risk relying on an indeterminate value of
errno
.
signal
: If the call tosignal
in a signal handler fails, the value oferrno
is indeterminate (see C11 Standard, Sec. 7.14.1.1). If you rely on a specific value oferrno
, you can see unexpected results.errno
-setting POSIX function: Anerrno
-setting function setserrno
on failure. If you readerrno
after a signal handler is called and the signal handler itself calls anerrno
-setting function, you can see unexpected results.
Fix
Avoid situations where you risk relying on an indeterminate value of
errno
.
signal
: After calling thesignal
function in a signal handler, do not readerrno
or use a function that readserrno
.errno
-setting POSIX function: Before calling anerrno
-setting function in a signal handler, saveerrno
to a temporary variable. Restoreerrno
from this variable before returning from the signal handler.
Examples
Result Information
Group: Programming |
Language: C | C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax:
SIG_HANDLER_ERRNO_MISUSE |
Impact: Medium |
Version History
Introduced in R2018a
See Also
Function called
from signal handler not asynchronous-safe
| Errno not checked
| Errno not reset
| Find defects (-checkers)
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)