afferify COPYING and the contrib folders
[oweals/gnunet.git] / contrib / timeout_watchdog.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2010 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License, or
8      (at your option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      Affero General Public License for more details.
14 */
15
16 /**
17  * @file contrib/timeout_watchdog.c
18  * @brief small tool starting a child process, waiting that it terminates or killing it after a given timeout period
19  * @author Matthias Wachs
20  */
21
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28
29 static pid_t child;
30
31
32 static void
33 sigchld_handler (int val)
34 {
35   int status = 0;
36   int ret = 0;
37
38   (void) val;
39   waitpid (child, &status, 0);
40   if (WIFEXITED (status) != 0)
41     {
42       ret = WEXITSTATUS (status);
43       printf ("Test process exited with result %u\n", ret);
44     }
45   if (WIFSIGNALED (status) != 0)
46     {
47       ret = WTERMSIG (status);
48       printf ("Test process was signaled %u\n", ret);
49     }
50   exit (ret);
51 }
52
53
54 static void
55 sigint_handler (int val)
56 {
57   kill (0, val);
58   exit (val);
59 }
60
61
62 int
63 main (int argc,
64       char *argv[])
65 {
66   int timeout = 0;
67   pid_t gpid = 0;
68
69   if (argc < 3)
70     {
71       printf
72         ("arg 1: timeout in sec., arg 2: executable, arg<n> arguments\n");
73       exit (1);
74     }
75
76   timeout = atoi (argv[1]);
77
78   if (timeout == 0)
79     timeout = 600;
80
81 /* with getpgid() it does not compile, but getpgrp is the BSD version and working */
82   gpid = getpgrp ();
83
84   signal (SIGCHLD, sigchld_handler);
85   signal (SIGABRT, sigint_handler);
86   signal (SIGFPE, sigint_handler);
87   signal (SIGILL, sigint_handler);
88   signal (SIGINT, sigint_handler);
89   signal (SIGSEGV, sigint_handler);
90   signal (SIGTERM, sigint_handler);
91
92   child = fork ();
93   if (child == 0)
94     {
95       /*  int setpgrp(pid_t pid, pid_t pgid); is not working on this machine */
96       //setpgrp (0, pid_t gpid);
97       if (-1 != gpid)
98         setpgid (0, gpid);
99       execvp (argv[2], &argv[2]);
100       exit (1);
101     }
102   if (child > 0)
103     {
104       sleep (timeout);
105       printf ("Child processes were killed after timeout of %u seconds\n",
106               timeout);
107       kill (0, SIGTERM);
108       exit (1);
109     }
110   exit (1);
111 }
112
113 /* end of timeout_watchdog.c */