~martijnbraam/postprocessd

80a9389a69f7020097512ccac9838abcb5f1d54e — Martijn Braam 2 years ago c8cc7f7 megapixels 0.2.1
Kill daemon at end of queue
1 files changed, 27 insertions(+), 2 deletions(-)

M main.c
M main.c => main.c +27 -2
@@ 5,6 5,7 @@
#include <sys/un.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <fcntl.h>
#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);
	}
}