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
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/wait.h>
char *const run_path[] = { "./run", NULL };
void
start_proc()
{
pid_t p = fork();
if (p == 0) {
execv(run_path[0], run_path);
} else if (p > 0) {
waitpid(p, NULL, 0);
} else {
err(1, "fork()");
}
}
int
acquire_lock()
{
int lock_fd;
if ((lock_fd = open("supervise/lock", O_CREAT | O_TRUNC | O_RDONLY, 0600)) == -1)
err(1, "open()");
if (flock(lock_fd, LOCK_EX | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK) {
fprintf(stderr, "Could not acquire lock\n");
exit(1);
} else {
err(1, "flock()");
}
}
return lock_fd;
}
void
update_status()
{
int fd, r;
unsigned char status[18];
if ((fd = open("supervise/status.new", O_CREAT | O_TRUNC | O_WRONLY | 0644)) == -1) {
perror("open()");
return;
}
if ((r = write(fd, status, sizeof(status))) == -1)
perror("write()");
if (close(fd) == -1)
perror("close()");
if (r < sizeof(status)) {
fprintf(stderr, "Failed to fully write status.new\n");
if (unlink("supervise/status.new") == -1)
perror("unlink()");
return;
}
if (rename("supervise/status.new", "supervise/status") == -1)
perror("rename()");
}
int
main(int argc, char **argv)
{
int lock_fd;
if (argc != 2)
errx(1, "Usage: %s <dir>\n", argv[0]);
if (chdir(argv[1]) == -1)
err(1, "chdir()");
if (mkdir("supervise", 0700) == -1 && errno != EEXIST)
err(1, "mkdir()");
lock_fd = acquire_lock();
if (mkfifo("supervise/control", 0600) == -1 && errno != EEXIST)
err(1, "mkfifo()");
if (mkfifo("supervise/ok", 0600) == -1 && errno != EEXIST)
err(1, "mkfifo()");
start_proc(); /* XXX: Main loop goes here */
if (close(lock_fd) == -1)
perror("close()");
return 0;
}
|