gpiomon: stop execution and exit cleanly on SIGINT or SIGTERM
authorBartosz Golaszewski <bartekgola@gmail.com>
Wed, 11 Jan 2017 12:18:07 +0000 (13:18 +0100)
committerBartosz Golaszewski <bartekgola@gmail.com>
Wed, 11 Jan 2017 12:18:07 +0000 (13:18 +0100)
Signed-off-by: Bartosz Golaszewski <bartekgola@gmail.com>
gpiomon.c

index 9b40472c97a00fa4cd52eab0b52ba3b5674afd75..f2ba13b9d6cd70d231971a4e11d5d4c09411af24 100644 (file)
--- a/gpiomon.c
+++ b/gpiomon.c
@@ -14,6 +14,7 @@
 #include <stdio.h>
 #include <string.h>
 #include <getopt.h>
+#include <signal.h>
 
 static const struct option longopts[] = {
        { "help",       no_argument,    NULL,   'h' },
@@ -33,6 +34,13 @@ static void print_help(void)
        printf("  -l, --active-low:\tset the line active state to low\n");
 }
 
+static volatile bool do_run = true;
+
+static void sighandler(int signum UNUSED)
+{
+       do_run = false;
+}
+
 static int event_callback(int type, const struct timespec *ts,
                          void *data UNUSED)
 {
@@ -53,6 +61,9 @@ static int event_callback(int type, const struct timespec *ts,
                printf("GPIO EVENT: %s [%8ld.%09ld]\n",
                       evname, ts->tv_sec, ts->tv_nsec);
 
+       if (!do_run)
+               return GPIOD_EVENT_CB_STOP;
+
        return GPIOD_EVENT_CB_OK;
 }
 
@@ -102,6 +113,9 @@ int main(int argc, char **argv)
        timeout.tv_sec = 0;
        timeout.tv_nsec = 500000000;
 
+       signal(SIGINT, sighandler);
+       signal(SIGTERM, sighandler);
+
        status = gpiod_simple_event_loop(device, offset, active_low,
                                         &timeout, event_callback, NULL);
        if (status < 0)