cf0ed01727c451276a6d59c41852999f32e1b6af
[build-farm.git] / timelimit.c
1 /* run a command with a limited timeout
2    tridge@samba.org, June 2005
3
4    attempt to be as portable as possible (fighting posix all the way)
5 */
6 #include <stdio.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <signal.h>
11 #include <errno.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14
15 static void usage(void)
16 {
17         printf("usage: timelimit <time> <command>\n");
18 }
19
20 static void sig_alrm(int sig)
21 {
22         fprintf(stderr, "\nMaximum time expired in timelimit - killing\n");
23         kill(0, SIGKILL);
24         exit(1);
25 }
26
27 int main(int argc, char *argv[])
28 {
29         int maxtime, ret=1;
30
31         if (argc < 3) {
32                 usage();
33                 exit(1);
34         }
35
36 #ifdef BSD_SETPGRP
37         if (setpgrp(0,0) == -1) {
38                 perror("setpgrp");
39                 exit(1);
40         }
41 #else
42         if (setpgrp() == -1) {
43                 perror("setpgrp");
44                 exit(1);
45         }
46 #endif
47
48         maxtime = atoi(argv[1]);
49         signal(SIGALRM, sig_alrm);
50         alarm(maxtime);
51
52         if (fork() == 0) {
53                 execvp(argv[2], argv+2);
54                 perror(argv[2]);
55                 exit(1);
56         }
57
58         do {
59                 int status;
60                 pid_t pid = wait(&status);
61                 if (pid != -1) {
62                         ret = WEXITSTATUS(status);
63                 } else if (errno == ECHILD) {
64                         break;
65                 }
66         } while (1);
67
68         exit(ret);
69 }