Skip to content

Instantly share code, notes, and snippets.

@dram
Created May 31, 2013 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dram/5683646 to your computer and use it in GitHub Desktop.
Save dram/5683646 to your computer and use it in GitHub Desktop.
Using signal and `pthread_kill` to terminate specific thread. `pthread_sigmask` can be used in thread to block signal temporarily.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
static void debug(const char *msg) {
time_t t = time(NULL);
fprintf(stderr, "%s%s\n\n", ctime(&t), msg);
}
static void handler(int signum)
{
pthread_exit(NULL);
}
void *thread(void *arg)
{
static sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGUSR1);
debug("Blocking SIGUSR1 in thread...");
if (pthread_sigmask(SIG_BLOCK, &mask, NULL) != 0) {
perror("pthread_sigmask");
exit(1);
}
debug("Do something...");
sleep(10);
debug("Unblocking SIGUSR1 in thread...");
if (pthread_sigmask(SIG_UNBLOCK, &mask, NULL) != 0) {
perror("pthread_sigmask");
exit(1);
}
debug("Will not reach here...");
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t tid;
signal(SIGUSR1, handler);
if (pthread_create(&tid, NULL, thread, NULL) != 0) {
perror("pthread_create");
exit(1);
}
sleep(5);
debug("Sending SIGUSR1 to thread...");
pthread_kill(tid, SIGUSR1);
pthread_join(tid, NULL);
debug("Thread exited.");
return 0;
}
@wagoodman
Copy link

keep in mind that pthread_exit is not a async-signal-safe function and shouldn't be called from a signal handler (http://man7.org/linux/man-pages/man7/signal-safety.7.html)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment