From 2dc7e9e6bd7f70fde6ea09bbb5372a11f90f698a Mon Sep 17 00:00:00 2001 From: Marius Halden Date: Fri, 27 Nov 2015 23:36:20 +0100 Subject: Added some of the initial implementation --- supervise.c | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 84 insertions(+), 1 deletion(-) (limited to 'supervise.c') diff --git a/supervise.c b/supervise.c index 3bae8cf..95ede21 100644 --- a/supervise.c +++ b/supervise.c @@ -3,19 +3,102 @@ #include #include #include +#include +#include +#include +#include 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 \n", argv[0]); if (chdir(argv[1]) == -1) err(1, "chdir()"); - execv(run_path[0], run_path); + 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; } -- cgit v1.2.3