March 2013
Intermediate to advanced
516 pages
15h 11m
English
Realistic applications need to shut down cleanly when interrupted with
Ctrl-C or another signal, such as SIGTERM. By default,
these simply kill the process, meaning messages won’t be flushed, files
won’t be closed cleanly, and so on.
Example 2-10 shows how we handle signals in various languages.
Example 2-10. Handling Ctrl-C cleanly (interrupt.c)
//// Shows how to handle Ctrl-C//#include <zmq.h>#include <stdio.h>#include <signal.h>// ---------------------------------------------------------------------// Signal handling//// Call s_catch_signals() in your application at startup, and then exit// your main loop if s_interrupted is ever 1. Works especially well with// zmq_poll.staticints_interrupted=0;staticvoids_signal_handler(intsignal_value){s_interrupted=1;}staticvoids_catch_signals(void){structsigactionaction;action.sa_handler=s_signal_handler;action.sa_flags=0;sigemptyset(&action.sa_mask);sigaction(SIGINT,&action,NULL);sigaction(SIGTERM,&action,NULL);}intmain(void){void*context=zmq_ctx_new();void*socket=zmq_socket(context,ZMQ_REP);zmq_bind(socket,"tcp://*:5555");s_catch_signals();while(1){// Blocking read will exit on a signalzmq_msg_tmessage;zmq_msg_init(&message);zmq_msg_recv(&message,socket,0);if(s_interrupted){printf("W: interrupt received, killing server...\n");break;}}zmq_close(socket);zmq_ctx_destroy(context);return0;}
The program provides s_catch_signals() ...
Read now
Unlock full access