问题
I'm trying to limit the max execution time of shell_exec in PHP to say 20 seconds and fetch whatever output is generated during this time. If shell_exec finishes in less than 20 seconds the script should proceed directly.
More specifically I'm developing a function that iterates through a large number of revisions of a subversion repository. For each revision it's fetching the svn diff and counts the number of lines added. The problem is that if very large files have been committed in a revision, the script will hang. Hence I'm trying to limit the execution time of each svn diff command.
popen() in combination with sleep() is not an option as it seems to make the script sleep for 20 seconds for each iteration which would not be viable with 100 iterations. Setting max_execution_time is also not an option as it would return a fatal error.
回答1:
popen() or proc_open is still an option, you just need to avoid sleep() and manage the execution time yourself.
$end = time() + 20;
while (!feof($stream) && (time() < $end)) {
$output .= fread($stream);
The popen stream should be set up non-blocking still:
stream_set_blocking($stream, 0);
Polling the output like this might be still a bit straining, so you should consider adding a small time_nanosleep() anyway. The runtime is limited to max 20 seconds by the time()<$end
check in either case.
来源:https://stackoverflow.com/questions/5950938/limit-execution-time-of-shell-exec-and-grab-whatever-output-is-generated