首頁  >  文章  >  後端開發  >  PHP如何建立單例後台程式方法介紹

PHP如何建立單例後台程式方法介紹

巴扎黑
巴扎黑原創
2017-08-13 11:30:591015瀏覽

這篇文章主要介紹了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如何建立單例後台程式方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn