X-Git-Url: https://code.citadel.org/?a=blobdiff_plain;f=webcit%2Fctdlsvc.c;h=865efc29854a0cb49790ec8de89209242e8e2314;hb=25bdf679e0136c2cfdf0dbfd7b5ba23d95a2acbd;hp=69c5277a944f5d384de04882b457f15167002484;hpb=65f351469eb40a4c711b491c36e1372b1f41f19b;p=citadel.git diff --git a/webcit/ctdlsvc.c b/webcit/ctdlsvc.c index 69c5277a9..865efc298 100644 --- a/webcit/ctdlsvc.c +++ b/webcit/ctdlsvc.c @@ -1,8 +1,8 @@ /* * $Id: $ * - * This is just a quick little hack to start a program and automatically - * restart it if it exits with a nonzero exit status. + * This is just a quick little hack to start a program in the background, + * and automatically restart it if it exits with a nonzero exit status. * */ @@ -12,36 +12,75 @@ #include #include #include +#include +char *pidfilename = NULL; +pid_t current_child = 0; + +RETSIGTYPE graceful_shutdown(int signum) { + kill(current_child, signum); + if (pidfilename != NULL) { + unlink(pidfilename); + } + exit(0); +} + int main(int argc, char **argv) { pid_t child = 0; int status = 0; + FILE *fp; + + --argc; + ++argv; + pidfilename = argv[0]; --argc; ++argv; + if (access(argv[0], X_OK)) { + fprintf(stderr, "%s: cannot execute\n", argv[0]); + exit(1); + } + + close(1); + close(2); + signal(SIGHUP, SIG_IGN); + signal(SIGINT, SIG_IGN); + signal(SIGQUIT, SIG_IGN); + + child = fork(); + if (child != 0) { + fp = fopen(pidfilename, "w"); + if (fp != NULL) { + fprintf(fp, "%d\n", child); + fclose(fp); + } + exit(0); + } + do { - child = fork(); + current_child = fork(); + + signal(SIGTERM, graceful_shutdown); - if (child < 0) { + if (current_child < 0) { perror("fork"); exit(errno); } - else if (child == 0) { + else if (current_child == 0) { exit(execvp(argv[0], &argv[0])); } else { - printf("%s: started. pid = %d\n", argv[0], child); - waitpid(child, &status, 0); - printf("Exit code %d\n", status); + waitpid(current_child, &status, 0); } } while (status != 0); + unlink(pidfilename); exit(0); }