这篇文章主要介绍了php创建单例后台进程的方法,涉及php针对进程的启动、创建、判断、停止等相关操作技巧,需要的朋友可以参考下
本文实例讲述了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
}
以上就是php如何创建单例后台进程方法介绍的详细内容。