#!/usr/bin/perl use strict; sub sys_alarm { my ( $cmd_result, $pid ); my $cmd = shift( @_ ); my $timeout = shift( @_ ); eval { local $SIG{ ALRM } = sub { kill -9, $pid; warn "timeout of command \"$cmd\"; killing $pid\n"; }; if ($pid = open(IN, "-|")) { alarm $timeout; while ( ) { $cmd_result .= $_; } close(IN); waitpid $pid, 0; alarm 0; } else { die "cannot fork: $!" unless defined $pid; setpgrp( 0, 0 ); exec( $cmd ); exit; } }; return $cmd_result; } my $x = sys_alarm("sleep 10; echo foo", 5); print "Output: " . $x . "\n\n";