Is a signal sent with kill to a parent thread guar

2019-09-06 12:04发布

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?

3条回答
2楼-- · 2019-09-06 12:38

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.

查看更多
时光不老,我们不散
3楼-- · 2019-09-06 12:41

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

kill(getpid(), someSignal);

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 have someSignal blocked (in which case, the sig handler will run from the thread calling kill).

See http://pubs.opengroup.org/onlinepubs/009695399/functions/kill.html :

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-09-06 12:42

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.

查看更多
登录 后发表回答