Fixed a problem with timelimit and child scripts that become children
authortridge <tridge@1e5ffdc8-eadd-0310-9daa-9cb4117fe24b>
Mon, 21 Nov 2005 01:02:53 +0000 (01:02 +0000)
committertridge <tridge@1e5ffdc8-eadd-0310-9daa-9cb4117fe24b>
Mon, 21 Nov 2005 01:02:53 +0000 (01:02 +0000)
of init. This ensures that all processes in the process group are
killed, regardless of whether they have been re-parented.

git-svn-id: file:///home/svn/build-farm/trunk@266 1e5ffdc8-eadd-0310-9daa-9cb4117fe24b

timelimit.c

index cf0ed01727c451276a6d59c41852999f32e1b6af..44c9618d1a476670a5dd30412ae9ed398b738d93 100644 (file)
@@ -12,6 +12,8 @@
 #include <sys/types.h>
 #include <sys/wait.h>
 
+static pid_t child_pid;
+
 static void usage(void)
 {
        printf("usage: timelimit <time> <command>\n");
@@ -20,19 +22,12 @@ static void usage(void)
 static void sig_alrm(int sig)
 {
        fprintf(stderr, "\nMaximum time expired in timelimit - killing\n");
-       kill(0, SIGKILL);
+       kill(-child_pid, SIGKILL);
        exit(1);
 }
 
-int main(int argc, char *argv[])
+static void new_process_group(void)
 {
-       int maxtime, ret=1;
-
-       if (argc < 3) {
-               usage();
-               exit(1);
-       }
-
 #ifdef BSD_SETPGRP
        if (setpgrp(0,0) == -1) {
                perror("setpgrp");
@@ -44,17 +39,32 @@ int main(int argc, char *argv[])
                exit(1);
        }
 #endif
+}
+
+
+int main(int argc, char *argv[])
+{
+       int maxtime, ret=1;
+       pid_t pgid;
+
+       if (argc < 3) {
+               usage();
+               exit(1);
+       }
 
        maxtime = atoi(argv[1]);
-       signal(SIGALRM, sig_alrm);
-       alarm(maxtime);
 
-       if (fork() == 0) {
+       child_pid = fork();
+       if (child_pid == 0) {
+               new_process_group();
                execvp(argv[2], argv+2);
                perror(argv[2]);
                exit(1);
        }
 
+       signal(SIGALRM, sig_alrm);
+       alarm(maxtime);
+
        do {
                int status;
                pid_t pid = wait(&status);
@@ -65,5 +75,7 @@ int main(int argc, char *argv[])
                }
        } while (1);
 
+       kill(-child_pid, SIGKILL);
+
        exit(ret);
 }