本文實(shí)例講述了PHP創(chuàng)建單例后臺(tái)進(jìn)程的方法。分享給大家供大家參考,具體如下:
可以通過如下語句啟動(dòng)一個(gè)PHP后臺(tái)進(jìn)程:
$command = " php script.php ";$pid = exec("nohup $command > /dev/null 2>&1 & echo $!");nohup表示這個(gè)進(jìn)程獨(dú)立于創(chuàng)建的用戶,可以以守護(hù)方式運(yùn)行。
如果需要這個(gè)后臺(tái)進(jìn)程是單例運(yùn)行的,那么可以通過下面的方法來記錄/判斷進(jìn)程是否已運(yùn)行
//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寫入文件,但如果在一個(gè)分布式任務(wù)環(huán)境中,則放在數(shù)據(jù)庫中要更好
停止一個(gè)后臺(tái)進(jìn)程:
//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}希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選