From 80a9389a69f7020097512ccac9838abcb5f1d54e Mon Sep 17 00:00:00 2001 From: Martijn Braam Date: Sat, 25 Jun 2022 16:55:26 +0200 Subject: [PATCH] Kill daemon at end of queue --- main.c | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/main.c b/main.c index 8361d55..16bd59c 100644 --- a/main.c +++ b/main.c @@ -5,6 +5,7 @@ #include #include #include +#include #include "util.h" #include "postprocess.h" @@ -31,7 +32,8 @@ is_daemon_running() struct timeval tv; // Daemon isn't running if the socket doesn't exist - if (!access(socket_path, F_OK)) { + if (access(socket_path, F_OK)) { + fprintf(stderr, "[fg] daemon socket doesn't exist\n"); return 0; } @@ -51,6 +53,7 @@ is_daemon_running() addr.sun_family = AF_UNIX; strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1); if (connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_un)) < 0) { + err("[fg] could not open daemon socket"); return 0; } @@ -140,6 +143,7 @@ start_background_process() unsigned int cli_len; struct Job job; char buffer[272]; + int first = 1; const char *name_fg = "postprocessd fg"; const char *name_bg = "postprocessd bg"; @@ -197,12 +201,29 @@ start_background_process() sock = listen_on_socket(); fprintf(stderr, "[bg] socket created\n"); + fprintf(stderr, "[bg] first accept start\n"); while (1) { fd = accept(sock, (struct sockaddr *) &cli_addr, &cli_len); - if (fd < 0) { + + if (fd < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + if (first) { + // When no queued item has been processed yet act like a proper nonblocking accept + // Doing a busy loop isn't very efficient but this should last for less than a second + usleep(100); + continue; + } + + // No client was available after processing the first image. Kill the background process + fprintf(stderr, "[bg] shutting down\n"); + close(sock); + unlink(socket_path); + exit(0); + } else if (fd < 0) { + // Something went wrong with the listening socket and it wasn't the nonblocking errnos err("[bg] failed to accept"); return 0; } + fprintf(stderr, "[bg] accepted connection\n"); if (read(fd, &job, sizeof(job)) < 0) { err("[bg] failed to read"); @@ -210,6 +231,7 @@ start_background_process() } fprintf(stderr, "[bg] start processing job\n"); start_processing(job); + first = 0; wait(NULL); fprintf(stderr, "[bg] job done\n"); @@ -219,6 +241,9 @@ start_background_process() err("[bg] failed to write response"); } close(fd); + + // Make the listen socket nonblocking + fcntl(sock, F_SETFL, O_NONBLOCK); } } -- 2.45.2