~emersion/blackbox

5b298bf4c1d7179ce8d1d5f1540bef62991f9d79 — Simon Ser 3 months ago 6314dde
Handle SIGINT/SIGTERM
1 files changed, 33 insertions(+), 1 deletions(-)

M main.c
M main.c => main.c +33 -1
@@ 1,6 1,7 @@
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>


@@ 61,6 62,14 @@ static int ring_buffer_write(struct ring_buffer *ring, int fd) {
	return 0;
}

static int sig_fd = -1;

static void handle_signal(int sig) {
	if (write(sig_fd, &sig, sizeof(sig) != sizeof(sig))) {
		abort();
	}
}

int main(int argc, char *argv[]) {
	int opt;
	while ((opt = getopt(argc, argv, "")) != -1) {


@@ 104,12 113,24 @@ int main(int argc, char *argv[]) {
		return 1;
	}

	int sig_pipe[2];
	if (pipe(sig_pipe) != 0) {
		perror("pipe failed");
		return 1;
	}
	sig_fd = sig_pipe[1];

	if (signal(SIGTERM, handle_signal) == SIG_ERR || signal(SIGINT, handle_signal) == SIG_ERR) {
		perror("signal failed");
		return 1;
	}

	fprintf(stderr, "Flight recorder started\n");
	fprintf(stderr, "To grab data, run: nc -dU %s\n", sockaddr.sun_path);

	static struct ring_buffer ring_buffer = {0};

	struct pollfd pollfds[2] = {0};
	struct pollfd pollfds[3] = {0};
	size_t pollfds_len = 0;

	struct pollfd *socket_pollfd = &pollfds[pollfds_len++];


@@ 120,8 141,15 @@ int main(int argc, char *argv[]) {
	in_pollfd->fd = in_fd;
	in_pollfd->events = POLLIN;

	struct pollfd *sig_pollfd = &pollfds[pollfds_len++];
	sig_pollfd->fd = sig_pipe[0];
	sig_pollfd->events = POLLIN;

	while (1) {
		if (poll(pollfds, pollfds_len, -1) < 0) {
			if (errno == EINTR) {
				continue;
			}
			perror("poll failed");
			return 1;
		}


@@ 151,6 179,10 @@ int main(int argc, char *argv[]) {

			close(fd);
		}

		if (sig_pollfd->revents & POLLIN) {
			break;
		}
	}

	unlink(sockaddr.sun_path);