PHP创建单例后台进程

来源:互联网 发布:c语言函数格式 编辑:程序博客网 时间:2024/06/11 18:17

可以通过如下语句启动一个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 runningexec("ps $pid", $pState);if((count($pState) >= 2) && !empty($pid)){echo "RUNNING";}else{echo "INACTIVE";}
也可以把pid写入文件,但如果在一个分布式任务环境中,则放在数据库中要更好


停止一个后台进程:

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



by iefreer