summaryrefslogtreecommitdiffstats
path: root/newbatch.c
blob: 0bac7ee5ca1ad5594c904e755ca394dbfeff4fb1 (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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
#include <err.h>
#include <string.h>
#include <fcntl.h>

#define DEFAULT_QUEUE_DIR "."

int
main(int argc, char **argv)
{
	pid_t mypid;
	struct timeval tv;
	int64_t microtime;
	char *timestr = NULL, *queuedir = NULL, *tmpfile = NULL, *newfile = NULL;
	char buf[1024], *tmp;
	int fd, l, m;
	int perm = 0640;

	mypid = getpid();
	gettimeofday(&tv, NULL);
	microtime = tv.tv_sec * 1000000 + tv.tv_usec;
	asprintf(&timestr, "%li.%u", microtime, mypid);

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

	asprintf(&tmpfile, "%s/tmp/%s", queuedir, timestr);
	asprintf(&newfile, "%s/new/%s", queuedir, timestr);
	free(timestr);
	free(queuedir);

	if (getenv("NEWBATCH_EXEC") != NULL) {
		perm = 0750;
	}

	fd = open(tmpfile, O_WRONLY | O_CREAT | O_EXCL, perm);
	if (fd == -1)
		err(1, "open()");

	while ((l = read(STDIN_FILENO, buf, sizeof(buf))) != 0) {
		if (l == -1) {
			if (errno == EINTR)
				continue;

			unlink(tmpfile);
			err(1, NULL);
		}

		tmp = buf;
		while (l > 0) {
			m = write(fd, tmp, l);
			if (m == -1) {
				if (errno == EINTR)
					continue;

				unlink(tmpfile);
				err(1, NULL);
			}
			l -= m;
			tmp += m;
		}
	}
	close(fd);

	if (rename(tmpfile, newfile) == -1) {
		unlink(tmpfile);
		err(1, NULL);
	}

	free(tmpfile);
	free(newfile);

	return 0;
}