#!/usr/bin/perl use strict; use warnings; use File::Temp ':POSIX'; use POSIX ':sys_wait_h'; my $timeout = 5; my @cmd=('perl', '-e', 'for(0..2){print qq(TEST $_\n); warn(qq(TTTT $_\n)); sleep(1); }'); my $tempfile = tmpnam(); my $output=''; die("ERROR create tempfile") unless($tempfile); # split in two independent processes my $pid = fork(); # fork failed! die('Fork failed!') unless(defined($pid)); if($pid) { # main process! my $time=time()+$timeout; # wait timeout seconds while($time > time()) { # is process running? if(waitpid($pid, WNOHANG) == 0) { # wait 0.3 seconds select(undef,undef,undef,0.3); # or do something else # ... } else { # exit while loop last(); } } # process running? if(waitpid($pid, WNOHANG)==0) { print "TIMEOUT KILL PROCESS\n"; # force exit (softly) kill(9, $pid); $output=''; unlink($tempfile); } else { # read written tempfile: if(open(my $fh, '<', $tempfile)) { local $/=undef; $output=<$fh>; close($fh); if( !unlink($tempfile) ) { warn("CAN'T REMOVE $tempfile ($!)\n"); } } else { warn("CAN'T OPEN $tempfile ($!)\n"); } } } else { # forked process! # reopen STDOUT STDERR open(STDOUT, '>', $tempfile) or die("ERROR open $tempfile ($!)"); open(STDERR, ">&STDOUT"); # start programm with actual process id exec(@cmd); # error??? die("EXEC Failed! ($!)"); } if($output) { print "OUTPUT:\n"; print $output; } else { print "NO OUTPUT!\n"; }