php exec() - max_execution_time and Fatal error

感情迁移 提交于 2020-01-24 16:14:24

问题


While resizing a bunch of images (about 9000), I use this function:

function im_call($_data, &$_im_output, $_debug = IM_DEBUG) {

  ini_set('max_execution_time', '3600');
  exec($_data, $_im_output, $_im_error); // this is line 93
  return $_im_error;

} // end function

And after a while (about 30 MINUTES) PHP dies with:

Fatal error: Maximum execution time of 30 seconds exceeded in /some/path/im_lib.php on line 93

(it is the line with exec()... )

How is this possible?


回答1:


System calls do not count to the PHP run time and so barely effect max_execution_time and set_time_limit. If you are calling your script from a webserver, you have to know that the webserver (not PHP) may drop the HTTP connection.

For example:

Apache default configuration:

# Timeout: The number of seconds before receives and sends time out.
#
Timeout 180

# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 15

Every 15 seconds, send a keep alive, repeat 100 times = 1515 seconds between HTTP Request start and closing of the connection. This is about 25 Minutes, almost half an hour. Even if this is about Webserver <> Client negotiation and not Webserver <> PHP, the webserver (and client!) still may simply drop the connections after a while.

Scripts taking longer than a few minutes should always run from console. HTTP Servers are not ment to keep a single request alive for hours.

Use PHP scripts from console (linux):

#!/usr/bin/php
<?php
/* code */

In combination with set_time_limit, the PHP garbage collector and the settings for more memory, those scripts can run for ages.

Appendix:

The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.

http://php.net/manual/en/function.set-time-limit.php




回答2:


Use set time limit

set_time_limit(0);


来源:https://stackoverflow.com/questions/18766989/php-exec-max-execution-time-and-fatal-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!