Search code examples
clinuxsignals

Why is the ANSI C signal() function considered bad?


I see warnings on the function's documentation and sometimes when it's mentioned on Stack Overflow saying that it's better to use the POSIX sigaction() function. The warnings say that on Linux the function may not behave as expected. What do they mean by that?

One of these warnings is in the description section here.


Solution

  • If all you want to do is catch a signal, once, signal is still kinda okay.

    The question is, after you catch it, what happens if the signal comes in a second time? Perhaps while the first signal handler is still running?

    Under different systems, there have been different answers.

    • Once upon a time, your signal handler got deregistered the first time it fired, meaning you had to reregister it every time, meaning there was a race condition if a second signal came in before you had a chance to reregister it.
    • Since then, various improvements have been made, such as having further signals be blocked while a signal handler is running, and having them not always deregister themselves, so you don't have to reregister them.

    But if you just call signal, you don't know which of these behaviors you're getting — but the differences probably matter to you.

    sigaction gives you explicit, predictable control over all these details, and is therefore preferred.

    See also the "Portability" subsection in the NOTES section in the man page you linked: https://man7.org/linux/man-pages/man2/signal.2.html#NOTES

    See also this previous SO question: What is the difference between sigaction and signal?