-
-
Save indutny/8361b2a97ec7e5149193 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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