Search code examples
phpajaxfindscriptinghung

Finding/Handling stalled PHP scripts


I use Ajax to kick off a PHP script that can take a few hours to run. It's done asynchronously so the PHP script will complete even if the browser is closed.

I need to handle any of these PHP scripts that have stalled/hung for whatever reason. What is the best way to go about this? Is there a way to get a process id for the PHP script that can be used to check for activity periodically? I need to kill any outstanding scripts before starting a new one.

Thanks, Brian


Solution

  • A solution might be based on this idea :

    • At the beginning of the long-running script, use getmypid to get its PID (Process Id)
    • store that PID in a file
    • At the end of the script, just before it ends, delete that file.

    When another process is launched, it can check if that file is present :

    • if it is and the process with the PID contained in the file is still running, di what you have to :
      • either kill it
      • or stop, considering one process running at the same time is enough
    • if the file is present, but the process with that PID is not, it means your first process died (like Fatal Error, for instance)
    • if the file is not present, it means the first process finished normally

    About detecting whether a process is running, and eventually killing it, I'm not sure if PHP provides that kind of functionnalities... It might be necessary to use exec to call command-line utilities like ps and kill...