ae978595c97b61f785cfa3544502277673843876
[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 # set CPU limit, in case the alarm handler will
42 # be ignored
43 eval {
44     require BSD::Resource;
45     BSD::Resource::setrlimit( "RLIMIT_CPU", $timeout, 2 * $timeout )
46       or die "Cannot set CPU limit: $!\n";
47 };
48 if ($@) {
49     warn
50       "WARNING: things would go more nicely with the BSD::Resource package\n";
51 }
52
53 #
54 # configure signal handlers
55 #
56 $SIG{ALRM} = sub {
57     my $pgid = getpgrp();
58
59     warn "Alarm handler got called after $timeout seconds\n";
60     warn "Kill now the process group $pgid\n\n";
61
62     # kill process group
63     kill "INT", -$pgid;
64 };
65
66 # don't kill ourself
67 $SIG{INT} = "IGNORE";
68
69 alarm($timeout);
70
71 system(@system) == 0
72   or die "system('@system') failed: ?='$?', !='$!', ^E='$^E'\n";
73
74 1;
75