From: Stephen L Johnson Date: Mon, 6 Aug 2001 23:07:25 +0000 (+0000) Subject: added into CVS X-Git-Tag: spong-2_4_6~7 X-Git-Url: http://git.etc.gen.nz/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c67aae42a774700d9c314eb50d2e79c1f21d2fb0;p=spong.git added into CVS --- diff --git a/src/lib/Spong/SafeExec.pm b/src/lib/Spong/SafeExec.pm new file mode 100755 index 0000000..86f1e6d --- /dev/null +++ b/src/lib/Spong/SafeExec.pm @@ -0,0 +1,58 @@ + +package Spong::SafeExec; + +use Carp qw(croak carp); +use Exporter (); + +use vars qw($VERSION @ISA @EXPORT_OK); + +$VERSION = 0.01; +@ISA = qw(Exporter); +@EXPORT_OK = qw(safe_exec); + +sub safe_exec { + my($cmd,$timeout) = @_; + my (@output); + + $timeout = 15 if $timeout <= 0; + + my $pid = open(CMD, "-|"); + + if ($pid) { # I'm the parent + + $message = ""; + eval { + local $SIG{'ALRM'} = sub { die }; + alarm($timeout); + + @output = ; + + alarm(0); + }; + + close CMD or !$! or croak "Error closing CMD fh: $!"; + alarm(0); + + # Handle child process is not gone + if ( kill 0,$pid ) { + kill "INTR",$pid; # Try control+C + sleep 1; # Give it time to die + + if ( kill 0, $pid ) { + kill 9,$pid; # If still alive, nuke it + if ( kill 0, $pid ) { + carp "Could not kill pid $pid"; + } + } + + } + + } else { + exec($cmd) || croak "cannot exec program $cmd: $!"; + } + + wantarray ? @output : join '', @output; +} + + +1;