views:

58

answers:

1

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

+4  A: 

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...

Pascal MARTIN
Thanks, very very helpful. Yes I can run it via exec. A couple more details: 1) Not all will take hours - some will only take minutes, 2) The restriction is one process per user, not total, and there may be dozens of users at a time or more.As a followup, is there an effective way for a PHP script to monitor resources so I don't potentially blow up my server?
Brian
If you are on a Linux server, maybe http://php.net/sys_getloadavg could do (depending on what you do) ;; if there are dozens of users and processes at a time, be careful not to "eat" too many Apache processes, as only MaxClients of them can run at the same time.
Pascal MARTIN
Thanks very much.
Brian