Handling Interrupt Signals
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.
static
int
s_interrupted
=
0
;
static
void
s_signal_handler
(
int
signal_value
)
{
s_interrupted
=
1
;
}
static
void
s_catch_signals
(
void
)
{
struct
sigaction
action
;
action
.
sa_handler
=
s_signal_handler
;
action
.
sa_flags
=
0
;
sigemptyset
(
&
action
.
sa_mask
);
sigaction
(
SIGINT
,
&
action
,
NULL
);
sigaction
(
SIGTERM
,
&
action
,
NULL
);
}
int
main
(
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 signal
zmq_msg_t
message
;
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
);
return
0
;
}
The program provides s_catch_signals() ...
Get ZeroMQ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.