#include #include #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()"); 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; }