From f2f0a815ccdecb9c65c6d661f9b57cc8ba0ab81e Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Fri, 25 Oct 2024 13:57:59 +0200 Subject: benutze atexit() zum Aufräumen der Bibliothek MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.c | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/main.c b/src/main.c index 9579568..9e806fe 100644 --- a/src/main.c +++ b/src/main.c @@ -10,6 +10,10 @@ // Project #include +#ifndef UNUSED +# define UNUSED(x) (void) (x) +#endif + #define CLIENT_ID "my-client-id" #define HOST "192.168.77.2" #define PORT 1883 @@ -21,7 +25,7 @@ static volatile bool terminate = false; // NOLINT -void +static void handler(int signal) { if ( signal == SIGINT ) { @@ -32,19 +36,26 @@ handler(int signal) static void message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) { - (void) obj; - (void) mosq; + UNUSED(obj); + UNUSED(mosq); printf("message '%.*s' for topic '%s'\n", message->payloadlen, (const char *) message->payload, message->topic); } +static void +cleanup(void) +{ + mosquitto_lib_cleanup(); +} + int main(void) { (void) signal(SIGINT, handler); mosquitto_lib_init(); + (void) atexit(cleanup); struct mosquitto *client = mosquitto_new(CLIENT_ID, true, NULL); if ( client == NULL ) { @@ -71,7 +82,9 @@ main(void) mosquitto_subscribe(client, NULL, TOPIC, 0); while ( !terminate ) { - err = mosquitto_loop(client, -1, 1); + static const int defaultTimeout = -1; // 1000ms + + err = mosquitto_loop(client, defaultTimeout, 1); if ( !terminate && err ) { (void) fprintf(stderr, "connection error: %s\n", mosquitto_strerror(err)); sleep(WAIT_UNTIL_RECONNECT); // NOLINT @@ -79,11 +92,9 @@ main(void) } } - printf("cleanup...\n"); + puts("shutdown..."); mosquitto_disconnect(client); mosquitto_destroy(client); - mosquitto_lib_cleanup(); - return EXIT_SUCCESS; } -- cgit v1.3