examples/notification: Catch CTRL-C to exit properly

pull/95/head
Olivier Martin 2019-05-03 09:47:18 +02:00
parent 71f33207c7
commit bcac05a811
1 changed files with 13 additions and 3 deletions

View File

@ -23,6 +23,7 @@
#include <assert.h> #include <assert.h>
#include <glib.h> #include <glib.h>
#include <signal.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@ -31,6 +32,8 @@
// Battery Level UUID // Battery Level UUID
const uuid_t g_battery_level_uuid = CREATE_UUID16(0x2A19); const uuid_t g_battery_level_uuid = CREATE_UUID16(0x2A19);
static GMainLoop *m_main_loop;
void notification_handler(const uuid_t* uuid, const uint8_t* data, size_t data_length, void* user_data) { void notification_handler(const uuid_t* uuid, const uint8_t* data, size_t data_length, void* user_data) {
int i; int i;
@ -42,6 +45,10 @@ void notification_handler(const uuid_t* uuid, const uint8_t* data, size_t data_l
printf("\n"); printf("\n");
} }
static void on_user_abort(int arg) {
g_main_loop_quit(m_main_loop);
}
static void usage(char *argv[]) { static void usage(char *argv[]) {
printf("%s <device_address>\n", argv[0]); printf("%s <device_address>\n", argv[0]);
} }
@ -69,12 +76,15 @@ int main(int argc, char *argv[]) {
goto DISCONNECT; goto DISCONNECT;
} }
GMainLoop *loop = g_main_loop_new(NULL, 0); // Catch CTRL-C
g_main_loop_run(loop); signal(SIGINT, on_user_abort);
m_main_loop = g_main_loop_new(NULL, 0);
g_main_loop_run(m_main_loop);
// In case we quit the main loop, clean the connection // In case we quit the main loop, clean the connection
gattlib_notification_stop(connection, &g_battery_level_uuid); gattlib_notification_stop(connection, &g_battery_level_uuid);
g_main_loop_unref(loop); g_main_loop_unref(m_main_loop);
DISCONNECT: DISCONNECT:
gattlib_disconnect(connection); gattlib_disconnect(connection);