pthread_kill doesnt kill thread C linux
Solution 1
pthread_kill()
will not kill a thread. The only difference with kill()
is that the signal is handled by the designated thread and not handled while that thread has the signal masked (see pthread_sigmask()
). A signal like SIGTERM
will by default still terminate the entire process.
If you are considering to call pthread_exit()
from a signal handler, you should probably use pthread_cancel()
instead.
Cancellation is safe if all code that may be cancelled cooperates (or the code that calls it disables cancellation for the time). Most libraries do not care about this, though.
A safer method is to ask the thread to exit without any force, such as by sending a special message to it (if the thread normally processes messages).
Alternatively, don't bother to kill any threads and just call _exit()
, _Exit()
or quick_exit()
.
Solution 2
From http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_kill.html
As in kill(), if sig is zero, error checking is performed but no signal is actually sent.
so the following
pthread_kill(threads[i].tID, 0);
Wont actually kill the thread. You need to use an actual signal to kill a thread. A list of signals can be found here:
http://pubs.opengroup.org/onlinepubs/7908799/xsh/signal.h.html
randy newfield
Updated on June 05, 2022Comments
-
randy newfield almost 2 years
i am making a small project which will be incorporated into larger project. basically what it does is keeps track of threads that are created by way of adding them to a main struct which keeps track of what the thread does (its main function) and its pthread_t id. the other struct keeps track of the data to be passed to the function and the element number of where the pthread_t id is stored inside threads[]. its a bit micky mouse and it jumps around a bit but it all works besides when it is time to kill the thread. i get no segfaults and no errors and the program finishes fine, but the thread does not get killed when pthread_kill() is called (the function returns 0 meaning no error and it worked) although the thread continues to run until the main application returns.
-
randy newfield about 12 yearsso i should send SIGKILL to my thread to make it kill? i was a bit confused about the signals and though sending '0' would mean exit with no errors or something around those lines
-
NothingMore about 12 yearsSIGKILL would force the thread to be killed. You could also look at using SIGTERM to kill a thread. rackerhacker.com/2010/03/18/sigterm-vs-sigkill Has a bit more information on the differences between KILL and TERM.
-
R.. GitHub STOP HELPING ICE about 12 yearsA signal can't kill a thread either. If it kills anything, it will kill the whole process.
-
R.. GitHub STOP HELPING ICE about 12 yearsNote that
pthread_exit
is not async signal safe, so the only way you can call it from a signal handler is if you ensure that signals are blocked whenever calling async-signal-unsafe functions.