开发者

Launch a process and get its return code or interrupt it if it lasts too long

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜