Debugging memory usage in mod_php

2020-07-25 06:49发布

问题:

I have a request handler running in apache/mod_php which occasionally expands beyond the maximum allowed memory usage (ie, the memory_limit definition in in php.ini).

Handling this request calls proc_open() to run external commands. Is the memory usage of those commands counted "against" the requests memory usage?

Beyond that, what are the preferred ways to analyze and fix memory usage of scripts running under mod_php? All the information I've found around php memory usage seems to be:

  • "Edit php.ini and raise the memory limit!"
  • "Edit your apache config and set max requests per child to a lower number!"

Obviously either of these can have a negative effect on performance and stability. How can I actually analyze and fix the problem, rather than band-aid it?

Apache logs the error as:

PHP Fatal error: Allowed memory size of X bytes exhausted (tried to allocate Y bytes) in foo.php on line Z

回答1:

I asked a similar question on PHP's memory management: Diagnosing Memory Leaks - Allowed memory size of # bytes exhausted

I'm fairly certain that running external programs from exec() or proc_open() does NOT count against php's memory limit.

Tracking memory usage in PHP is apparently very difficult. There doesn't appear to be a way to look up a symbol table or anything like that.

PHP has a couple memory management functions, like memory_get_usage() and memory_get_peak_usage(), that can fetch the total amount of memory used at any given point in your script. You could write your own tracking script and place it, ad-hoc, at key points to find memory hoggers.

Depending on how large your code-stack is, xdebug's execution trace may be your best bet. But this can be overkill if you have lots of code.