7e9ab0aff6e63ff412a2b52b9c343dad53429939
[mkws-moved-to-github.git] / test / bin / bomb.pl
1 #!/usr/bin/perl
2 # Copyright (c) 2014 Index Data ApS. http://indexdata.com
3 #
4 # bomb.pl - wrapper to stop a process after N seconds
5 #
6
7 use Getopt::Long;
8 use POSIX ":sys_wait_h";
9
10 use strict;
11 use warnings;
12
13 my $debug = 0;
14 my $help;
15 my $timeout = 100;
16 my $pid;
17
18 binmode \*STDOUT, ":utf8";
19 binmode \*STDERR, ":utf8";
20
21 sub usage () {
22     <<EOF;
23 usage: $0 [ options ] command args ....
24
25 --debug=0..3    debug option, default: $debug
26 --timeout=1..N  timeout in seconds, default: $timeout
27 EOF
28 }
29
30 GetOptions(
31     "help"      => \$help,
32     "debug=i"   => \$debug,
33     "timeout=f" => \$timeout,
34 ) or die usage;
35
36 my @system = @ARGV;
37
38 die usage if $help;
39 die usage if !@system;
40
41 # disabled - we set the CPU limit in the wrapper ./bomb
42 ## set CPU limit, in case the alarm handler will
43 ## be ignored
44 #eval {
45 #    require BSD::Resource;
46 #    BSD::Resource::setrlimit( "RLIMIT_CPU", $timeout, 2 * $timeout )
47 #      or die "Cannot set CPU limit: $!\n";
48 #};
49 #if ($@) {
50 #    warn
51 #      "WARNING: things would go more nicely with the BSD::Resource package\n";
52 #}
53
54 #
55 # configure signal handlers
56 #
57 $SIG{ALRM} = sub {
58     my $pgid = getpgrp();
59
60     warn "Alarm handler got called after $timeout seconds\n";
61     warn "Kill now the process group $pgid\n\n";
62
63     # kill process group
64     kill "INT", -$pgid;
65 };
66
67 # don't kill ourself
68 $SIG{INT} = "IGNORE";
69
70 alarm($timeout);
71
72 system(@system) == 0
73   or die "system('@system') failed: ?='$?', !='$!', ^E='$^E'\n";
74
75 1;