The company name is: Index Data
[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) or die "Cannot set CPU limit: $!\n";
46 };
47 if ($@) {
48     warn "WARNING: things would go more nicely with the BSD::Resource package\n";
49 }
50
51
52 #
53 # use fork/exec instead system()
54 #
55 $pid = fork();
56 die "fork() failed: $!" unless defined $pid;
57
58 # child
59 if ($pid) {
60     alarm($timeout);
61     exec(@system) or die "exec @system: $!\n";
62 }
63
64 # parent
65 else { }
66
67 1;