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
|
#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;
mypid = getpid();
gettimeofday(&tv, NULL);
microtime = tv.tv_sec * 1000000 + tv.tv_usec;
asprintf(×tr, "%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);
fd = open(tmpfile, O_WRONLY | O_CREAT | O_EXCL, 0660);
if (fd == -1)
err(1, "open()");
while ((l = read(STDIN_FILENO, buf, sizeof(buf))) != 0) {
if (l == -1) {
unlink(tmpfile);
err(1, NULL);
}
tmp = buf;
while (l > 0) {
m = write(fd, tmp, l);
if (m == -1) {
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;
}
|