Signal Handling – Choices for Dealing with Signals

signalstrap:

From APUE

A process has three choices for dealing with a signal.

  1. Ignore the signal. This option isn’t recommended for signals that denote a hardware exception, such as dividing by zero or
    referencing memory outside the address space of the process, as the
    results are undefined.

  2. Let the default action occur. For a divide-by-zero condition, the default is to terminate the process.

  3. Provide a function that is called when the signal occurs (this is called ‘‘catching’’ the signal). By providing a function of our own,
    we’ll know when the signal occurs and we can handle it as we wish.

  1. I think there is only two choices – the last two listed above, and
    both of them can "ignore the signal" (the first choice listed
    above).

    Is my understanding correct, or are there indeed three
    nonoverlapping choices as in the quote? Why?

  2. The book mentions that the default action of some signal is to
    ignore it. Does it mean the action of the signal is SIG_IGN or
    SIG_DFL or an empty function? For example:

    The default action for SIGCHLD is to be ignored. We describe these options in Chapter 10.

    SIGCONT: The default action is to continue a stopped process, but to ignore the signal if the process wasn’t
    stopped.

Thanks.

Best Answer

Of course one can write a signal handler that does nothing, and thus effectively ignoring the signal, but the first option is to specifically ignore the signal by using the SIG_IGN argument the signal() system call.

So in terms of code, assuming the SIGINT signal, these are the three options:

  • signal(SIGINT, SIG_IGN); to ignore
  • To not call the signal() function, or to call it with signal(SIGINT, SIG_DFL); and thus to let the default action occur, i.e. to terminate the process
  • signal(SIGINT, termination_handler);, where termination_handler() is a function that is called the first time the signal occurs.

Source: https://www.gnu.org/software/libc/manual/html_node/Basic-Signal-Handling.html

For the specific case of signals were the default action is to ignore the signal, the two first options (SIG_IGN and SIG_DFL) are identical. Creating an empty handler function probably won't have a visible effect, other than a (small) overhead.

NOTE: The signal() is used in this answer for simplicity, but in new code sigaction() is recommended for reasons of portability.

Related Question