简体   繁体   中英

Is a signal sent with kill to a parent thread guaranteed to be processed before the next statement?

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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM