Attachment 'timeout.c'
Download 1 #include <sys/types.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <errno.h>
7 #include <string.h>
8
9 int main(int argc, char *argv[])
10 {
11 const pid_t parent = getpid();
12 int timeout;
13
14 if (argc < 3) {
15 fprintf(stderr, "Usage: %s TIMEOUT COMMAND [ARG]...\n", argv[0]);
16 return 2;
17 }
18 timeout = strtol(argv[1], NULL, 10);
19 if (timeout <= 0) {
20 fprintf(stderr, "%s: %s: Invalid argument\n", argv[0], argv[1]);
21 return 2;
22 }
23
24 switch (fork()) {
25 case -1: { // fork failed
26 fprintf(stderr, "%s: %s\n", argv[0], strerror(errno));
27 return 126;
28 }
29 case 0: { // this is the child, a parricidal watchdog
30 int seconds;
31 fclose(stdin);
32 fclose(stdout);
33 fclose(stderr);
34 for (seconds = 0; seconds < timeout; seconds++) {
35 sleep(1);
36 if (kill(parent, 0) == -1) // has the parent already finished?
37 return 0; // okay, there's nothing left to do
38 }
39 kill(parent, SIGTERM);
40 sleep(5);
41 kill(parent, SIGKILL);
42 return 0;
43 }
44 default: { // this is the parent
45 execvp(argv[2], &argv[2]);
46 // upon success, execvp will not return here
47 if (errno == 2) {
48 fprintf(stderr, "%s: %s: Command not found\n", argv[0], argv[2]);
49 return 127; // not found
50 } else {
51 fprintf(stderr, "%s: %s: %s\n", argv[0], argv[2], strerror(errno));
52 return 126; // not executable
53 }
54 }
55 }
56 }
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.