Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a stack trace of a running or hung PHP script

I have a script that runs from a cron job every night. Recently, it has started totally freezing up after several minutes into the script, and I can't figure out why. If this was Java, I could simply run kill -3 PID and it would print a thread dump in stdout. Is there any equivalent in PHP, where I could get a dump of the current stack trace (and ideally memory info) on a running PHP script?

like image 608
Cory Gagliardi Avatar asked Jan 10 '13 15:01

Cory Gagliardi


People also ask

What is PHP stack trace?

But, what is a stack trace? In essence, it is a rundown of every file and function that is called leading up to the error. To be clear, a stack trace doesn't include the files and functions that are touched before the error occurred, only the chain of methods that are called as the error happened.

What is a backtrace PHP?

Definition and Usage. The debug_backtrace() function generates a PHP backtrace. This function displays data from the code that led up to the debug_backtrace() function. Returns an array of associative arrays.

How do I read stack trace in Visual Studio?

To open the Call Stack window in Visual Studio, from the Debug menu, choose Windows>Call Stack. To set the local context to a particular row in the stack trace display, select and hold (or double click) the first column of the row.


1 Answers

The best thing you can do is compile PHP yourself using --enable-debug during configure. If the process then still hangs you can use gdb and some macros to get a PHP-level stacktrace using these steps:

$ gdb -p $PHP_PID
(gdb) bt     # Get a system-level stacktrace, might already give some info
(gdb) source /path/to/php-src/.gdbinit # Load some useful macros
(gdb) dump_bt executor_globals.current_execute_data
            # Macro from PHP's .gbinit giving PHP stack trace
            # If you for whatever reason are using a thread-safe PHP build you have to do this:
(gdb) ____executor_globals
(gdb) dump_bt $eg.current_execute_data

And then debug ahead :-)

Note that for this to work you have to have a PHP binary with symbol information, --enable-debug ensures that.

like image 152
johannes Avatar answered Sep 27 '22 21:09

johannes