Skip to content

Commit a80ce1b

Browse files
committed
Add signal handler
1 parent 57dd74c commit a80ce1b

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

examples/mqtt-client/main.c

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@ static const char *s_pub_topic = "mg/clnt/test";
1919
static int s_qos = 1;
2020
static struct mg_connection *s_conn;
2121

22+
// Handle interrupts, like Ctrl-C
23+
static int s_signo;
24+
static void signal_handler(int signo) {
25+
s_signo = signo;
26+
}
27+
2228
static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
2329
if (ev == MG_EV_OPEN) {
2430
LOG(LL_INFO, ("CREATED"));
@@ -70,9 +76,12 @@ int main(void) {
7076
struct mg_timer timer;
7177
int topts = MG_TIMER_REPEAT | MG_TIMER_RUN_NOW;
7278

79+
signal(SIGINT, signal_handler); // Setup signal handlers - exist event
80+
signal(SIGTERM, signal_handler); // manager loop on SIGINT and SIGTERM
81+
7382
mg_mgr_init(&mgr); // Init event manager
7483
mg_timer_init(&timer, 3000, topts, timer_fn, &mgr); // Init timer
75-
for (;;) mg_mgr_poll(&mgr, 1000); // Event loop, 1s timeout
84+
while (s_signo == 0) mg_mgr_poll(&mgr, 1000); // Event loop, 1s timeout
7685
mg_mgr_free(&mgr); // Finished, cleanup
7786
mg_timer_free(&timer); // Free timer resources
7887

0 commit comments

Comments
 (0)