summaryrefslogtreecommitdiffstats
path: root/batchd.c
blob: ceb391157180303b248467732910fa73e14c971f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <errno.h>
#include <err.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <signal.h>

#define DEFAULT_QUEUE_DIR "."
#define MAX_JOBS 2

int cur_jobs = 0;

void
run_job(char *queuedir, int fd)
{
	char *run;
	switch(fork()) {
	case -1:
		return;
	case 0:
		asprintf(&run, "%s/run", queuedir);
		dup2(fd, STDIN_FILENO);
		close(fd);
		execl(run, "run", (char*)NULL);
		perror("execle()");
		_exit(1);
		break;
	}
}

void
process_queue(char *queuedir, int dfd)
{
	int fd;
	DIR *dir;
	struct dirent *de;
	char *name;

	dir = fdopendir(dfd);
	while ((de = readdir(dir))) {
		if (cur_jobs >= MAX_JOBS)
			break;

		if (strcmp(de->d_name, ".") == 0  || strcmp(de->d_name, "..") == 0)
			continue;

		asprintf(&name, "new/%s", de->d_name);

		fd = open(name, O_RDONLY);
		if (fd == -1) {
			free(name);
			continue;
		}
		unlink(name);
		run_job(queuedir, fd);
		close(fd);
		free(name);
		cur_jobs++;
	}
	
	rewinddir(dir);
	fdclosedir(dir);
}

void
wait_all()
{
	for (;;) {
		int r = waitpid(-1, NULL, WNOHANG);
		if (r == 0)
			break;
		else if (r == -1) {
			if (errno == ECHILD)
				break;
			else
				err(1, "waitpid()");
		}
		cur_jobs--;
	}
}

int
main(int argc, char **argv)
{
	int kq, dfd, ret;
	struct kevent kv[2];
	char *queuedir = NULL, *newdir = NULL;

	if (argc > 1) {
		queuedir = strdup(argv[1]);
	} else {
		queuedir = strdup(DEFAULT_QUEUE_DIR);
	}

	asprintf(&newdir, "%s/new", queuedir);

	dfd = open(newdir, O_RDONLY | O_DIRECTORY);
	if (dfd == -1)
		err(1, "open()");

	kq = kqueue();
	if (kq == -1)
		err(1, "kqueue()");

	EV_SET(&kv[0], dfd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE, 0, NULL);
	EV_SET(&kv[1], SIGCHLD, EVFILT_SIGNAL, EV_ADD | EV_CLEAR, 0, 0, NULL);

	if (kevent(kq, kv, 2, NULL, 0, NULL) == -1)
		err(1, "kevent()");

	process_queue(queuedir, dfd);

	for (;;) {
		ret = kevent(kq, NULL, 0, kv, 2, NULL);
		if (ret == 0)
			continue;
		else if (ret == -1) {
			if (errno  == EINTR)
				continue;
			else
				break;
		}

		int i;
		for (i = 0; i < ret; i++) {
			if (kv[i].filter == EVFILT_SIGNAL) {
				if (kv[i].ident == SIGCHLD) {
					wait_all();
					process_queue(queuedir, dfd);
				}
			} else if (kv[i].filter == EVFILT_VNODE) {
				process_queue(queuedir, dfd);
			}
		}
	}

	return 0;
}