1 /* run a command with a limited timeout
2 tridge@samba.org, June 2005
3 metze@samba.org, March 2006
5 attempt to be as portable as possible (fighting posix all the way)
13 #include <sys/types.h>
16 static pid_t child_pid;
18 static void usage(void)
20 printf("usage: timelimit <time> <command>\n");
21 printf(" SIGUSR1 - passes SIGTERM to command's process group\n");
22 printf(" SIGALRM - passes SIGTERM to command's process group\n");
23 printf(" after 5s SIGKILL will be passed and exit(1)\n");
24 printf(" SIGTERM - passes SIGTERM to command's process group\n");
25 printf(" after 1s SIGKILL will be passed and exit(1)\n");
26 printf(" SIGINT - handled like SIGTERM\n");
27 printf(" SIGQUIT - handled like SIGTERM\n");
30 static void sig_alrm_kill(int sig)
32 fprintf(stderr, "\nMaximum time expired in timelimit - killing\n");
33 kill(-child_pid, SIGKILL);
37 static void sig_alrm_term(int sig)
39 kill(-child_pid, SIGTERM);
41 signal(SIGALRM, sig_alrm_kill);
44 static void sig_term(int sig)
46 kill(-child_pid, SIGTERM);
48 signal(SIGALRM, sig_alrm_kill);
51 static void sig_usr1(int sig)
53 kill(-child_pid, SIGTERM);
56 static void new_process_group(void)
58 if (setpgid(0,0) == -1) {
65 int main(int argc, char *argv[])
74 maxtime = atoi(argv[1]);
79 execvp(argv[2], argv+2);
84 signal(SIGTERM, sig_term);
85 signal(SIGINT, sig_term);
86 signal(SIGQUIT, sig_term);
87 signal(SIGUSR1, sig_usr1);
88 signal(SIGALRM, sig_alrm_term);
93 pid_t pid = wait(&status);
95 if (WIFEXITED(status)) {
96 ret = WEXITSTATUS(status);
98 } else if (errno == ECHILD) {
103 kill(-child_pid, SIGKILL);