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";
}
虽然可以将进程ID保存至文件,但在分布式任务架构下,将其存储于数据库更为适宜。
终止正在运行的后台进程操作如下:
//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后台进程的核心控制技巧。