shell_exec() timeout management & exec()
I would suggest you look into using proc_open
. You can configure it to return a stream resource, manually keep a timer, and if the timer expires before the process completes, you can terminate it with proc_terminate
. If it does complete before the timer expires, then you can use proc_close
then stream_get_contents
to grab the data that would have otherwise been written to stdout.
See http://www.php.net/manual/en/function.proc-open.php
I write some working piece of code for such task. Function returns exit code (0 - OK, >0 - error) and writes stdout, stderr to reference variables.
/*execute program and write all output to $out
terminate program if it runs more than 30 seconds */
execute("program --option", null, $out, $out, 30);
echo $out;
function execute($cmd, $stdin=null, &$stdout, &$stderr, $timeout=false)
{
$pipes = array();
$process = proc_open(
$cmd,
array(array('pipe','r'),array('pipe','w'),array('pipe','w')),
$pipes
);
$start = time();
$stdout = '';
$stderr = '';
if(is_resource($process))
{
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
fwrite($pipes[0], $stdin);
fclose($pipes[0]);
}
while(is_resource($process))
{
//echo ".";
$stdout .= stream_get_contents($pipes[1]);
$stderr .= stream_get_contents($pipes[2]);
if($timeout !== false && time() - $start > $timeout)
{
proc_terminate($process, 9);
return 1;
}
$status = proc_get_status($process);
if(!$status['running'])
{
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
return $status['exitcode'];
}
usleep(100000);
}
return 1;
}