现在的位置: 首页 > 综合 > 正文

PHP创建单例后台进程

2013年09月14日 ⁄ 综合 ⁄ 共 669字 ⁄ 字号 评论关闭

可以通过如下语句启动一个PHP后台进程:

$command = " php script.php ";
$pid = exec("nohup $command > /dev/null 2>&1 & echo $!");

nohup表示这个进程独立于创建的用户,可以以守护方式运行。

如果需要这个后台进程是单例运行的,那么可以通过下面的方法来记录/判断进程是否已运行

//query the database for process id
$query = "SELECT pid FROM `daemons` WHERE `pid` = '2013' LIMIT 1";
$result = mysql_query($query);
$pid = mysql_result($result, 0, 'pid');
//check if the process is running
exec("ps $pid", $pState);
if((count($pState) >= 2) && !empty($pid))
{
echo "RUNNING";
}
else
{
echo "INACTIVE";
}

也可以把pid写入文件,但如果在一个分布式任务环境中,则放在数据库中要更好

停止一个后台进程:

//check if the process from the database is running
exec("ps $pid", $pState);
if((count($pState) >= 2))
{
//if the process is running, kill it
exec("kill $pid");
//update database row with an empty process id
}

by iefreer

抱歉!评论已关闭.