views:

59

answers:

1

Hello,

I have a PHP script launched from a command-line (aka CLI mode, no webserver involved).

In this script I launch a command that will run from some time, usually exiting after a couple minutes. But at times, this command will run for hours because of various issues, and the best I can do is kill it and wait for a while before launching it again.

Two things I want to emphasize :

  • I have no control of the code inside that command, and can't improve failure detection.
  • It's not an important task, and it's perfectly ok to have it working that way.

That being said, I would like to improve things in my code, so that I can kill the child process if the command has been running for more than N seconds. But I still want to get the return code from the command, when it runs fine.

Pseudo-code should be something like this :

Launch command
While command is running
{
    If the command is done running
    {
        echo return code
    }
    else
    {
        If the command has been running for more than N seconds
        {
            Kill the child process
        }
    }
}

How would you implement this in PHP ?

Thank you !

Solution : I ended up using the SIG_ALERT signal. More info on the signals handling and the pcntl lib in the pages provided by Gordon in his post.

+1  A: 

Read through this Chapter of Practical PHP Programming. It covers interoperating with Processes extensively. And also have a look at the PHP Manual's pages on Process Control.

You might also be interested in Gearman

Sorry for not providing any code. I never had the need for Process Control stuff, so I just kept in memory where to look in case I'd ever need it.

Gordon
I know about Gearman, Bearstalk and messaging queues in general, and I actually use Gearman in the very same project, but for a totally different purpose. Here I don't need queueing...I just want to run that command and kill it if it takes too much time.No problem at all for not providing code. It looks like the links you provide are going to be usefull to me :)
Nicolas
Cool. You're welcome.
Gordon