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>
20 char *pidfilename = NULL;
21 pid_t current_child = 0;
23 void graceful_shutdown(int signum) {
24 kill(current_child, signum);
25 if (pidfilename != NULL) {
32 int main(int argc, char **argv)
42 pidfilename = argv[0];
46 if (access(argv[0], X_OK)) {
47 fprintf(stderr, "%s: cannot execute\n", argv[0]);
51 /* Close stdin/stdout/stderr and replace them with /dev/null.
52 * We don't just call close() because we don't want these fd's
53 * to be reused for other files.
56 nullfd = open("/dev/null", O_RDWR);
58 fprintf(stderr, "/dev/null: %s\n", strerror(errno));
66 signal(SIGHUP, SIG_IGN);
67 signal(SIGINT, SIG_IGN);
68 signal(SIGQUIT, SIG_IGN);
72 fp = fopen(pidfilename, "w");
74 fprintf(fp, "%d\n", child);
83 freopen("/dev/null", "r", stdin);
84 freopen("/dev/null", "w", stdout);
85 freopen("/dev/null", "w", stderr);
88 current_child = fork();
90 signal(SIGTERM, graceful_shutdown);
92 if (current_child < 0) {
97 else if (current_child == 0) {
98 exit(execvp(argv[0], &argv[0]));
102 waitpid(current_child, &status, 0);
105 } while (status != 0);