-
[PHP] timeout이 있는 shell_exec 만들기개발 & 계발/PHP 2015. 1. 12. 13:47반응형
function shell_exec_timeout($cmd, $timeout)
{
if(!$cmd || !$timeout) return NULL;// File descriptors passed to the process.
$descriptors = array(
0 => array('pipe', 'r'), // stdin
1 => array('pipe', 'w'), // stdout
2 => array('pipe', 'w') // stderr
);// Start the process.
$process = proc_open($cmd, $descriptors, $pipes);if (!is_resource($process))
{
throw new Exception('Could not execute process');
}// Set the stdout stream to none-blocking.
stream_set_blocking($pipes[1], 0);// Turn the timeout into microseconds.
$timeout = $timeout * 1000000;// Output buffer.
$buffer = '';// While we have time to wait.
while ($timeout > 0)
{
$start = microtime(true);// Wait until we have output or the timer expired.
$read = array($pipes[1]);
$other = array();stream_select($read, $other, $other, 0, $timeout);
// Get the status of the process.
// Do this before we read from the stream,
// this way we can't lose the last bit of output if the process dies between these functions.
$status = proc_get_status($process);// Read the contents from the buffer.
// This function will always return immediately as the stream is none-blocking.
$buffer .= stream_get_contents($pipes[1]);if (!$status['running'])
{
// Break from this loop if the process exited before the timeout.
break;
}// Subtract the number of microseconds that we waited.
//$timeout -= (microtime(true) - $start) * 1000000;$during = (microtime(true) - $start) * 1000000;
$timeout = $timeout - $during;
} // while ($timeout > 0)proc_terminate($process, 9);
// Close all streams.
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);proc_close($process);
return $buffer;
} // function shell_exec_timeout($cmd, $timeout)'개발 & 계발 > PHP' 카테고리의 다른 글
[PHP] shell에서 문자열 입력 받기 (0) 2015.06.25 달력 심플 소스 (0) 2015.02.25 CURL & fsockopen 업무 향상을 위한 샘플 (0) 2014.09.15 [PHP] preg_match 등 정규식 만들때 사용되는 Pattern Modifier 자료 (0) 2014.08.18 [PHP] FTP_PUT 사용 방법 (0) 2014.06.20