Parameter | Details |
---|---|
sig | The signal to set the signal handler to, one of SIGABRT , SIGFPE , SIGILL , SIGTERM , SIGINT , SIGSEGV or some implementation defined value |
func | The signal handler, which is either of the following: SIG_DFL , for the default handler, SIG_IGN to ignore the signal, or a function pointer with the signature void foo(int sig); . |
The usage of signal handlers with only the guarantees from the C standard imposes various limitations what can, or can't be done in the user defined signal handler.
If the user defined function returns while handling SIGSEGV
, SIGFPE
, SIGILL
or any other implementation-defined hardware interrupt, the behavior is undefined by the C standard. This is because C's interface doesn't give means to change the faulty state (e.g after a division by 0
) and thus when returning the program is in exactly the same erroneous state than before the hardware interrupt occurred.
If the user defined function was called as the result of a call to abort
, or raise
, the signal handler is not allowed to call raise
, again.
Signals can arrive in the middle of any operation, and therefore the indivisibility of operations can in generally not be guaranteed nor does signal handling work well with optimization. Therefore all modifications to data in a signal handler must be to variables
sig_atomic_t
(all versions) or a lock-free atomic type (since C11, optional)volatile
qualified.Other functions from the C standard library will usually not respect these restrictions, because they may change variables in the global state of the program. The C standard only makes guarantees for abort
, _Exit
(since C99), quick_exit
(since C11), signal
(for the same signal number), and some atomic operations (since C11).
Behavior is undefined by the C standard if any of the rules above are violated. Platforms may have specific extensions, but these are generally not portable beyond that platform.
Usually systems have their own list of functions that are asynchronous signal safe, that is of C library functions that can be used from a signal handler. E.g often printf
is among these function.
In particular the C standard doesn't define much about the interaction with its threads interface (since C11) or any platform specific thread libraries such as POSIX threads. Such platforms have to specify the interaction of such thread libraries with signals by themselves.