Last active
January 3, 2016 06:59
-
-
Save mhaberler/8426050 to your computer and use it in GitHub Desktop.
example for synchronous signal processing with czmq/zloop using signalfd(2)
This file contains hidden or 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
// example for synchronous signal processing with czmq/zloop using signalfd(2) | |
// Michael Haberler 1/2014 | |
#include <czmq.h> | |
#include <sys/signalfd.h> | |
int signo; | |
static int s_handle_signal(zloop_t *loop, zmq_pollitem_t *poller, void *arg) | |
{ | |
struct signalfd_siginfo fdsi; | |
ssize_t s = read(poller->fd, &fdsi, sizeof(struct signalfd_siginfo)); | |
if (s != sizeof(struct signalfd_siginfo)) { | |
perror("read"); | |
} | |
fprintf(stderr, "got ignal %d '%s'\n",fdsi.ssi_signo,strsignal(fdsi.ssi_signo) ); | |
signo = fdsi.ssi_signo; | |
return -1; // exit reactor | |
} | |
int main(int argc, char **argv) | |
{ | |
int sfd, retval; | |
// suppress default handling of signals in zctx_new() | |
// since we're using signalfd() - must happen before zctx_new() | |
zsys_handler_set(NULL); | |
void *ctx = zctx_new(); | |
assert(ctx); | |
zloop_t *loop = zloop_new(); | |
assert (loop); | |
sigset_t sigmask; | |
sigemptyset(&sigmask); | |
// block all signal delivery through default signal handlers | |
// since we're using signalfd() | |
sigfillset(&sigmask); | |
sigprocmask(SIG_SETMASK, &sigmask, NULL); | |
// explicitly enable signals we want delivered via signalfd() | |
sigemptyset(&sigmask); | |
sigaddset(&sigmask, SIGINT); | |
sigaddset(&sigmask, SIGQUIT); | |
sigaddset(&sigmask, SIGTERM); | |
sigaddset(&sigmask, SIGSEGV); | |
sigaddset(&sigmask, SIGFPE); | |
// only here it is safe to create threads with zthread() since | |
// the sigmask is inherited from the main thread | |
sfd = signalfd(-1, &sigmask, 0); | |
assert(sfd != -1); | |
zmq_pollitem_t signal_poller = { 0, sfd, ZMQ_POLLIN }; | |
zloop_poller (loop, &signal_poller, s_handle_signal, NULL); | |
do { | |
retval = zloop_start(loop); | |
} while (!retval); | |
if (signo) | |
fprintf(stderr, "exiting by signal %d\n", signo); | |
exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
changes:
Resetting the default signal handling with zsys_set_handler(NULL) must happen before a context is created.
Dont use side effects in assert() statements - in case this is compiled with -DNDEBUG .