source: signal.c @ f3b5dc8

Last change on this file since f3b5dc8 was f3b5dc8, checked in by David Benjamin <davidben@mit.edu>, 10 years ago
Reset signal dispositions and mask, in case our parent was lame Also check return values more carefully.
  • Property mode set to 100644
File size: 1.5 KB
Line 
1#include <glib.h>
2#include <errno.h>
3#include <pthread.h>
4#include <signal.h>
5#include <stdio.h>
6#include <stdlib.h>
7
8static GThread *signal_thread;
9static sigset_t signal_set;
10
11static void (*signal_cb)(int, void*);
12static void *signal_cbdata;
13
14static gpointer signal_thread_func(gpointer data);
15
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.) */
22void owl_signal_init(const sigset_t *set, void (*callback)(int, void*), void *data) {
23  GError *error = NULL;
24  int ret;
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. */
30  if ((ret = pthread_sigmask(SIG_BLOCK, set, NULL)) != 0) {
31    errno = ret;
32    perror("pthread_sigmask");
33  }
34  /* Spawn a dedicated thread to sigwait. */
35  signal_thread = g_thread_create(signal_thread_func, NULL, FALSE, &error);
36  if (signal_thread == NULL) {
37    fprintf(stderr, "Failed to create signal thread: %s\n", error->message);
38    exit(1);
39  }
40}
41
42static gpointer signal_thread_func(gpointer data) {
43  while (1) {
44     int signal;
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
52    signal_cb(signal, signal_cbdata);
53  }
54  return NULL;
55}
Note: See TracBrowser for help on using the repository browser.