#!/usr/bin/perl
-# Copyright (c) 2014 IndexData ApS. http://indexdata.com
+# Copyright (c) 2014 Index Data ApS. http://indexdata.com
#
# bomb.pl - wrapper to stop a process after N seconds
#
die usage if $help;
die usage if !@system;
+# set CPU limit, in case the alarm handler will
+# be ignored
+eval {
+ require BSD::Resource;
+ BSD::Resource::setrlimit( "RLIMIT_CPU", $timeout, 2 * $timeout )
+ or die "Cannot set CPU limit: $!\n";
+};
+if ($@) {
+ warn
+ "WARNING: things would go more nicely with the BSD::Resource package\n";
+}
+
#
-# use fork/exec instead system()
+# configure signal handlers
#
-$pid = fork();
-die "fork() failed: $!" unless defined $pid;
+$SIG{ALRM} = sub {
+ my $pgid = getpgrp();
-# child
-if ($pid) {
- alarm($timeout);
- exec(@system) or die "exec @system: $!\n";
-}
+ warn "Alarm handler got called after $timeout seconds\n";
+ warn "Kill now the process group $pgid\n\n";
+
+ # kill process group
+ kill "INT", -$pgid;
+};
+
+# don't kill ourself
+$SIG{INT} = "IGNORE";
+
+alarm($timeout);
-# parent
-else { }
+system(@system) == 0
+ or die "system('@system') failed: ?='$?', !='$!', ^E='$^E'\n";
1;