4 * This is just a quick little hack to start a program in the background,
5 * and automatically restart it if it exits with a nonzero exit status.
12 #include <sys/types.h>
19 char *pidfilename = NULL;
20 pid_t current_child = 0;
22 void graceful_shutdown(int signum) {
23 kill(current_child, signum);
24 if (pidfilename != NULL) {
31 int main(int argc, char **argv)
41 pidfilename = argv[0];
45 if (access(argv[0], X_OK)) {
46 fprintf(stderr, "%s: cannot execute\n", argv[0]);
50 /* Close stdin/stdout/stderr and replace them with /dev/null.
51 * We don't just call close() because we don't want these fd's
52 * to be reused for other files.
54 nullfd = open("/dev/null", O_RDWR);
56 fprintf(stderr, "/dev/null: %s\n", strerror(errno));
64 signal(SIGHUP, SIG_IGN);
65 signal(SIGINT, SIG_IGN);
66 signal(SIGQUIT, SIG_IGN);
70 fp = fopen(pidfilename, "w");
72 fprintf(fp, "%d\n", child);
79 current_child = fork();
81 signal(SIGTERM, graceful_shutdown);
83 if (current_child < 0) {
88 else if (current_child == 0) {
89 exit(execvp(argv[0], &argv[0]));
93 waitpid(current_child, &status, 0);
96 } while (status != 0);