randy newfield
randy newfield

Reputation: 1221

pthread_kill doesnt kill thread C linux

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.

Upvotes: 2

Views: 15448

Answers (2)

jilles
jilles

Reputation: 11252

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

Upvotes: 6

NothingMore
NothingMore

Reputation: 1281

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

Upvotes: 4

Related Questions