`
jishublog
  • 浏览: 871666 次
文章分类
社区版块
存档分类
最新评论

PHP创建单例后台进程

 
阅读更多

可以通过如下语句启动一个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



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics