make the package BSD::Resource optional
[mkws-moved-to-github.git] / test / bin / bomb.pl
index a84f40b..bff7f68 100755 (executable)
@@ -1,10 +1,11 @@
-#!/usr/local/bin/perl
+#!/usr/bin/perl
 # Copyright (c) 2014 IndexData ApS. http://indexdata.com
 #
 # bomb.pl - wrapper to stop a process after N seconds
 #
 
 use Getopt::Long;
+use POSIX ":sys_wait_h";
 
 use strict;
 use warnings;
@@ -12,39 +13,11 @@ use warnings;
 my $debug = 0;
 my $help;
 my $timeout = 100;
+my $pid;
 
 binmode \*STDOUT, ":utf8";
 binmode \*STDERR, ":utf8";
 
-# timeout handler
-sub set_alarm {
-    my $time = shift;
-    my $message = shift || "";
-
-    $time = 100 if !defined $time;
-
-    $SIG{ALRM} = sub {
-
-        warn "Time out alarm $time\n";
-
-        # sends a hang-up signal to all processes in the current process group
-        # and kill running java processes
-        local $SIG{HUP} = "IGNORE";
-        kill 1, -$$;
-
-        local $SIG{TERM} = "IGNORE";
-        kill 15, -$$;
-        kill 15, -$$;
-
-        warn "Send a hang-up to all childs.\n";
-
-        #exit 1;
-    };
-
-    warn "set alarm time to: $time seconds $message\n" if $debug >= 1;
-    alarm($time);
-}
-
 sub usage () {
     <<EOF;
 usage: $0 [ options ] command args ....
@@ -57,7 +30,7 @@ EOF
 GetOptions(
     "help"      => \$help,
     "debug=i"   => \$debug,
-    "timeout=i" => \$timeout,
+    "timeout=f" => \$timeout,
 ) or die usage;
 
 my @system = @ARGV;
@@ -65,9 +38,30 @@ my @system = @ARGV;
 die usage if $help;
 die usage if !@system;
 
-set_alarm( $timeout, join( " ", @system ) );
+# set CPU limit, in case the alarm handler will
+# be ignored
+eval {
+    require BSD::Resource2;
+    setrlimit("RLIMIT_CPU", $timeout, 2*$timeout) or die "Cannot set CPU limit: $!\n";
+};
+if ($@) {
+    warn "Please install the package BSD::Resource!\n\n$@\n";
+}
+
+
+#
+# use fork/exec instead system()
+#
+$pid = fork();
+die "fork() failed: $!" unless defined $pid;
+
+# child
+if ($pid) {
+    alarm($timeout);
+    exec(@system) or die "exec @system: $!\n";
+}
 
-system(@system) == 0
-  or die "system @system failed: $?";
+# parent
+else { }
 
-exit(0);
+1;