Skip to content

Instantly share code, notes, and snippets.

@mhaberler
Last active January 3, 2016 06:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhaberler/8426050 to your computer and use it in GitHub Desktop.
Save mhaberler/8426050 to your computer and use it in GitHub Desktop.
example for synchronous signal processing with czmq/zloop using signalfd(2)
// 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);
}
@mhaberler
Copy link
Author

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 .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment