Search code examples
linuxprocesssignals

After kill(getpid(), sig), is the signal guaranteed to be delivered before the next statement?


Assuming that you're in a single-threaded process, and that the relevant signal is not blocked or ignored, is it guaranteed that:

kill(getpid(), sig);

will result in the signal being delivered before the next line of code is executed?

In particular, if the signal is one for which there is no handler and whole default action is to terminate the process (e.g. SIGTERM, SIGALRM), is it guaranteed that the next line of code won't be executed?

I had always assumed that (at least on Linux) the answer was "yes", because I thought that before returning from any syscall the kernel would always check to see if there were any pending signals and deliver them if so. But I think I have observed that (when run on a heavily-loaded, multi-core system) this is not always the case, though this is very hard to reproduce and so I'd appreciate confirmation that I'm not seeing things.

[This question is very similar to Is a signal sent with kill to a parent thread guaranteed to be processed before the next statement? except that that question was asking about multi-threaded processes (for which the answer is definitely "no"), whereas this question is about single-threaded processes.]


Solution

  • Yes. If you're in a single threaded process, POSIX gives guarantees you this.

    If the value of pid causes sig to be generated for the sending process, and if sig is not blocked for the calling thread and if no other thread has sig unblocked or is waiting in a sigwait() function for sig, either sig or at least one pending unblocked signal shall be delivered to the sending thread before kill() returns.