Okay, so if I'm running in a child thread on linux (using pthreads if that matters), and I run the following command
kill(getpid(), someSignal);
it will send the given signal to the parent of the current thread.
My question: Is it guaranteed that the parent will then immediately get the CPU and process the signal (killing the app if it's a SIGKILL or doing whatever else if it's some other signal) before the statement following kill()
is run? Or is it possible - even probable - that whatever command follows kill()
will run before the signal is processed by the parent thread?
No, it's not guaranteed.
In general, you cannot make any assumptions about the timing of events happening in separate threads (or processes) unless you use an explicit synchronization mechanism (for example, a phtread_mutex or a semaphore).
This is especially true on multi-CPU (or multi-core) systems, where multiple threads can be running literally simultaneously on separate CPUs, but even on a single-CPU system there are no guarantees.
Signals sent to a process (thread group) may generally get delivered to any thread, and you generally have no guarantee that the handler will have finished before the
kill
call returns.If you run
in a multithreaded process then you can only be sure that your sighandler will run before
kill
returns in a very specific scenario, where all but the calling threads havesomeSignal
blocked (in which case, the sig handler will run from the thread callingkill
).See http://pubs.opengroup.org/onlinepubs/009695399/functions/kill.html :
Signals get delivered asynchronously, so you can't expect the thread handling them to handle them immediately; moreover, it will have to do some work to handle it.
And if a sigprocmask() call had masked the signal in all threads, the signal will only be acted upon after it is unmasked.
Signals don't go to any particular thread, unless you have used sigprocmask to mask them from the threads you don't want to get them. Most multithreaded programs do this, as having process-level signals delivered to arbitrary threads is usually not what you want.