summaryrefslogtreecommitdiffabout
path: root/tests/to.c
blob: 6511a549bcecf3d56406cf1b3cee201ce4b3f5b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int
main (int argc, char **argv)
{
  char *progname = argv[0];
  unsigned long n;
  char *p;
  pid_t pid, ret;
  int status;
  
  if (argc < 3)
    {
      fprintf (stderr, "usage: %s TIMEOUT COMMAND ...\n", progname);
      exit (1);
    }
  errno = 0;
  n = strtoul (argv[1], &p, 10);
  if (errno || *p || n == 0)
    {
      fprintf (stderr, "%s: %s is not a valid timeout\n", progname, argv[1]);
      exit (1);
    }

  argc -= 2;
  argv += 2;

  pid = fork ();
  if (pid == -1)
    {
      perror ("fork");
      exit (127);
    }
  
  if (pid == 0)
    {
      execvp (argv[0], argv);
      perror (argv[0]);
      exit (127);
    }

  alarm (n);
  ret = wait (&status);
  alarm (0);

  if (ret != pid)
    {
      perror ("wait");
      exit (127);
    }

  if (WIFEXITED (status))
    return WEXITSTATUS (status);
  
  if (WIFSIGNALED (status))
    fprintf (stderr, "%s: %s terminated on signal %d\n", progname, argv[0],
	     WTERMSIG (status));
  else if (WIFSTOPPED (status))
    fprintf (stderr, "%s: %s stopped\n", progname, argv[0]);
  else
    fprintf (stderr, "%s: %s exited with unrecognized status %d\n",
	     progname, argv[0], status);
  return 127;
}
    
      
  
  
	

Return to:

Send suggestions and report system problems to the System administrator.