Skip to content

Instantly share code, notes, and snippets.

@indutny

indutny/sig.c Secret

Created August 27, 2012 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indutny/8361b2a97ec7e5149193 to your computer and use it in GitHub Desktop.
Save indutny/8361b2a97ec7e5149193 to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <pthread.h>
#define NUM_THREADS 4
void* signal_watcher(void* arg) {
int kq;
int numevents;
struct kevent event;
kq = kqueue();
EV_SET(&event, SIGINT, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0, 0);
numevents = kevent(kq, &event, 1, NULL, 0, NULL);
assert(numevents == 0);
for (;;) {
numevents = kevent(kq, NULL, 0, &event, 1, NULL);
if (numevents < 0) {
if (errno == EINTR) continue;
fprintf(stderr, "Unexpected error: %d\n", errno);
abort();
}
fprintf(stdout, "received signal\n");
break;
}
}
int main() {
int i;
int r;
pthread_t threads[NUM_THREADS];
struct sigaction sigact;
/* Ignore SIGINT */
memset(&sigact, 0, sizeof(sigact));
sigact.sa_handler = SIG_IGN;
sigaction(SIGINT, &sigact, NULL);
for (i = 0; i < NUM_THREADS; i++) {
r = pthread_create(&threads[i], NULL, signal_watcher, NULL);
assert(r == 0);
}
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment