[fafb842] | 1 | #include <glib.h> |
---|
[f3b5dc8] | 2 | #include <errno.h> |
---|
[fafb842] | 3 | #include <pthread.h> |
---|
| 4 | #include <signal.h> |
---|
| 5 | #include <stdio.h> |
---|
| 6 | #include <stdlib.h> |
---|
| 7 | |
---|
| 8 | static GThread *signal_thread; |
---|
| 9 | static sigset_t signal_set; |
---|
| 10 | |
---|
| 11 | static void (*signal_cb)(int, void*); |
---|
| 12 | static void *signal_cbdata; |
---|
| 13 | |
---|
| 14 | static gpointer signal_thread_func(gpointer data); |
---|
| 15 | |
---|
[87833a8] | 16 | /* Initializes the signal thread to listen for 'set' on a dedicated |
---|
| 17 | * thread. 'callback' is called *on the signal thread* when a signal |
---|
| 18 | * is received. |
---|
| 19 | * |
---|
| 20 | * This function /must/ be called before any other threads are |
---|
| 21 | * created. (Otherwise the signals will not get blocked correctly.) */ |
---|
[fafb842] | 22 | void owl_signal_init(const sigset_t *set, void (*callback)(int, void*), void *data) { |
---|
| 23 | GError *error = NULL; |
---|
[f3b5dc8] | 24 | int ret; |
---|
[fafb842] | 25 | |
---|
| 26 | signal_set = *set; |
---|
| 27 | signal_cb = callback; |
---|
| 28 | signal_cbdata = data; |
---|
| 29 | /* Block these signals in all threads, so we can get them. */ |
---|
[f3b5dc8] | 30 | if ((ret = pthread_sigmask(SIG_BLOCK, set, NULL)) != 0) { |
---|
| 31 | errno = ret; |
---|
| 32 | perror("pthread_sigmask"); |
---|
| 33 | } |
---|
[fafb842] | 34 | /* Spawn a dedicated thread to sigwait. */ |
---|
[87833a8] | 35 | signal_thread = g_thread_create(signal_thread_func, NULL, FALSE, &error); |
---|
[fafb842] | 36 | if (signal_thread == NULL) { |
---|
| 37 | fprintf(stderr, "Failed to create signal thread: %s\n", error->message); |
---|
| 38 | exit(1); |
---|
| 39 | } |
---|
| 40 | } |
---|
| 41 | |
---|
| 42 | static gpointer signal_thread_func(gpointer data) { |
---|
| 43 | while (1) { |
---|
[87833a8] | 44 | int signal; |
---|
[fafb842] | 45 | int ret; |
---|
| 46 | |
---|
| 47 | ret = sigwait(&signal_set, &signal); |
---|
| 48 | /* TODO: Print an error? man page claims it never errors. */ |
---|
| 49 | if (ret != 0) |
---|
| 50 | continue; |
---|
| 51 | |
---|
[87833a8] | 52 | signal_cb(signal, signal_cbdata); |
---|
[fafb842] | 53 | } |
---|
| 54 | return NULL; |
---|
| 55 | } |
---|