source: signal.c @ 81db142

release-1.10release-1.8release-1.9
Last change on this file since 81db142 was 81db142, checked in by David Benjamin <davidben@mit.edu>, 13 years ago
Make owl_signal_init take a signal-thread callback Instead of pushing the work directly the main thread. This will allow us to react to SIGINT earlier.
  • Property mode set to 100644
File size: 1.4 KB
Line 
1#include <glib.h>
2#include <pthread.h>
3#include <signal.h>
4#include <stdio.h>
5#include <stdlib.h>
6
7static GThread *signal_thread;
8static sigset_t signal_set;
9
10static void (*signal_cb)(int, void*);
11static void *signal_cbdata;
12
13static gpointer signal_thread_func(gpointer data);
14
15/* Initializes the signal thread to listen for 'set' on a dedicated
16 * thread. 'callback' is called *on the signal thread* when a signal
17 * is received.
18 *
19 * This function /must/ be called before any other threads are
20 * created. (Otherwise the signals will not get blocked correctly.) */
21void owl_signal_init(const sigset_t *set, void (*callback)(int, void*), void *data) {
22  GError *error = NULL;
23
24  signal_set = *set;
25  signal_cb = callback;
26  signal_cbdata = data;
27  /* Block these signals in all threads, so we can get them. */
28  pthread_sigmask(SIG_BLOCK, set, NULL);
29  /* Spawn a dedicated thread to sigwait. */
30  signal_thread = g_thread_create(signal_thread_func, NULL, FALSE, &error);
31  if (signal_thread == NULL) {
32    fprintf(stderr, "Failed to create signal thread: %s\n", error->message);
33    exit(1);
34  }
35}
36
37static gpointer signal_thread_func(gpointer data) {
38  while (1) {
39     int signal;
40    int ret;
41
42    ret = sigwait(&signal_set, &signal);
43    /* TODO: Print an error? man page claims it never errors. */
44    if (ret != 0)
45      continue;
46
47    signal_cb(signal, signal_cbdata);
48  }
49  return NULL;
50}
Note: See TracBrowser for help on using the repository browser.