sample/event-read-fifo: add proper exit path

Co-authored-by: Azat Khuzhin <azat@libevent.org>
This commit is contained in:
icy17 2024-04-22 15:11:15 +08:00 committed by Azat Khuzhin
parent 09738283d9
commit 25f4439dbd

View File

@ -84,7 +84,7 @@ signal_cb(evutil_socket_t fd, short event, void *arg)
int int
main(int argc, char **argv) main(int argc, char **argv)
{ {
struct event *evfifo; struct event *evfifo = NULL;
struct event_base* base; struct event_base* base;
#ifdef _WIN32 #ifdef _WIN32
HANDLE socket; HANDLE socket;
@ -101,7 +101,7 @@ main(int argc, char **argv)
return 1; return 1;
#else #else
struct event *signal_int; struct event *signal_int = NULL;
struct stat st; struct stat st;
const char *fifo = "event.fifo"; const char *fifo = "event.fifo";
int socket; int socket;
@ -141,18 +141,27 @@ main(int argc, char **argv)
signal_int = evsignal_new(base, SIGINT, signal_cb, base); signal_int = evsignal_new(base, SIGINT, signal_cb, base);
if (signal_int == NULL) { if (signal_int == NULL) {
perror("evsignal_new"); perror("evsignal_new");
exit(1); goto err;
} }
event_add(signal_int, NULL); event_add(signal_int, NULL);
evfifo = event_new(base, socket, EV_READ|EV_PERSIST, fifo_read, evfifo = event_new(base, socket, EV_READ|EV_PERSIST, fifo_read,
event_self_cbarg()); event_self_cbarg());
#endif #endif
if (evfifo == NULL) {
perror("event_new");
goto err;
}
/* Add it to the active events, without a timeout */ /* Add it to the active events, without a timeout */
event_add(evfifo, NULL); event_add(evfifo, NULL);
event_base_dispatch(base); event_base_dispatch(base);
#ifndef _WIN32
event_free(signal_int);
#endif
event_free(evfifo);
event_base_free(base); event_base_free(base);
#ifdef _WIN32 #ifdef _WIN32
CloseHandle(socket); CloseHandle(socket);
@ -161,6 +170,22 @@ main(int argc, char **argv)
unlink(fifo); unlink(fifo);
#endif #endif
libevent_global_shutdown(); libevent_global_shutdown();
return (0); return 0;
}
err:
#ifndef _WIN32
if (signal_int)
event_free(signal_int);
#endif
if (evfifo)
event_free(evfifo);
event_base_free(base);
#ifdef _WIN32
CloseHandle(socket);
#else
close(socket);
unlink(fifo);
#endif
libevent_global_shutdown();
return 1;
}