Finding / handling stuck PHP scripts
I am using Ajax to run a PHP script which can take hours. This is done asynchronously, so the PHP script will terminate even if the browser is closed.
I need to handle any of these PHP scripts that are hanging / freezing for whatever reason. What's the best way to do this? Is there a way to get the process id of a PHP script that can be used to periodically check for activity? I need to kill all outstanding scripts before starting a new one.
Thanks, Brian
source to share
The solution can be based on this idea:
- At the start of a long script use
getmypid
to get your PID (process id) - save this PID to file
- At the end of the script, before it ends, delete that file.
When another process starts, it can check if this file is present:
- if so, and the process with the PID contained in the file is still running, then what you need is:
- either kill him
- or stopping, since one process running at a time is sufficient.
- if the file is present, but the process with this PID is not, it means that your first process died (for example, Fatal Error)
- If the file is missing, it means that the first process exited normally
About detecting if a process is running and ultimately killing it, I'm not sure PHP provides such functionality ... It might need to be used exec
to invoke command line utilities like ps
and kill
...
source to share