cunixsigaction

Sigaction declaration in functions


Is sigaction in Unix declared only once in main function, or should I declare it inside every function my main calls, so if a signal comes when the execution is not inside my main, the signal handler will invoke? So, do I have to declare sigaction only once at the start of main() or do I have to declare it in every function?


Solution

  • You don't have to call sigaction() in every function. It sets a (global) signal handler for a given signal which remains the signal handler until you change it — by another call to sigaction() for the same signal. You can call sigaction() in main(), but that is not obligatory either. You can call it in selected other functions.

    Note that you need to call sigaction() once for each different signal that you want to handle — or ignore. It is often beneficial to call a function which loops over a list of signals, setting the appropriate handler(s) for each signal. Thank goodness you don't have to do that in each function you call!

    In general, avoid mixing calls to signal() and sigaction() in the same program. If you're using sigaction() anywhere, use it everywhere. However, if you insist on being perverse, then you can use "sigaction() or signal()" in the first paragraph where I only mentioned sigaction().

    Note that you can use sigaction() to find out how a signal is handled without setting new signal handling. With signal() you can find out (more or less) how the signal was being handled, but you have to set an action as well. Just another reason to prefer sigaction() over signal().

    Note that I'm assuming that 'declare' in the question means 'call' in some shape or form. You don't declare sigaction() in any function; you include <signal.h> to declare it.