summaryrefslogtreecommitdiffstats
path: root/batchd.c
blob: f3480bab066c44c6285ef47a3742ca2519010a80 (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
#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>

#define DEFAULT_QUEUE_DIR "."

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);
	default:
		wait(NULL);
	}
}

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

	dir = fdopendir(dfd);
	while ((de = readdir(dir))) {
		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);
	}
	
	rewinddir(dir);
	fdclosedir(dir);
}

int
main(int argc, char **argv)
{
	int kq, dfd, ret;
	struct kevent kv;
	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, dfd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE, 0, NULL);

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

	process_queue(queuedir, dfd);

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

		process_queue(queuedir, dfd);
	}

	return 0;
}