C Language Signal handling

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


  • void (*signal(int sig, void (*func)(int)))(int);


sigThe signal to set the signal handler to, one of SIGABRT, SIGFPE, SIGILL, SIGTERM, SIGINT, SIGSEGV or some implementation defined value
funcThe 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

    • of type sig_atomic_t (all versions) or a lock-free atomic type (since C11, optional)
    • that are 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.

Got any C Language Question?