#!/usr/bin/perl use strict; use warnings; use IO::Pipe; use POSIX qw(:sys_wait_h); my $timeout = 5; my @cmd=('perl', '-e', '$|=1; for(0..2){print qq(TEST $_\n); warn(qq(TTTT $_\n)); sleep(1); }'); my $output=''; # create pipe my $pipe = IO::Pipe->new(); # split in two independent processes my $pid = fork(); # fork failed! die('Fork failed!') unless(defined($pid)); if($pid) { # main process! $pipe->reader(); $pipe->blocking(0); my $time=time()+$timeout; # wait timeout seconds while($time > time()) { # is process running? if(waitpid($pid, WNOHANG) == 0) { # read all aviable if(my @data=<$pipe>) { $output.=join('',@data); } # do something else print "WAIT\n"; select(undef,undef,undef,0.3); # ... } else { # exit while loop last(); } } # process running? if(waitpid($pid, WNOHANG)==0) { print "TIMEOUT KILL PROCESS\n"; # force exit (softly) kill(9, $pid); $output=''; } } else { # forked process! $pipe->writer(); $pipe->autoflush(1); # reopen STDOUT and STDERR open(STDOUT, ">&", $pipe); open(STDERR, ">&STDOUT"); close($pipe); # start programm with actual process id exec(@cmd); # error??? die("EXEC Failed! ($!)"); } if($output) { print "OUTPUT:\n"; print $output; } else { print "NO OUTPUT!\n"; }