Created
January 12, 2014 03:59
-
-
Save pricejn2/8380648 to your computer and use it in GitHub Desktop.
script execution from php with timeout (alternate)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment