PHP也是可以直接進行守護進程的啟動與終止的,相對於shell來說會簡單很多,理解更方便,當然了PHP守護進程要實現自動重啟還是要依賴於shell的crontab議程表,每隔一段時間去執行一次指令碼看指令碼是否需要重啟,如果需要則殺掉進程刪除RunFile檔案,重新啟動並在RunFile檔案中寫入pid。
<?php function start($file){ $path = dirname(__FILE__).'/'; $runfile = $path.$file.'.run'; $diefile = $path.$file.'.die'; $file = $path."data/{$file}.php"; clearstatcache(); if(file_exists($runfile)){ $oldpid = file_get_contents($runfile); $nowpid = shell_exec("ps aux | grep 'php -f process.php' | grep ${oldpid} | awk '{print $2}'"); //如果runfile中的pid號可以匹配到正在啟動並執行,並且上次訪問runfile的時間和現在相差小於5min則返回 if(($oldpid == $nowpid) && (time() - fileatime($runfile) < 300)){ echo "$file is circle runing no"; return; }else{ //pid號不匹配或者已經有300秒沒有運行迴圈語句,直接殺掉進程,重新啟動 $pid = file_get_contents($runfile); shell_exec("ps aux | grep 'php -f process.php' | grep {$pid} | xargs --if-no-run-empty kill"); } }else{ //將檔案pid寫入run檔案 if(!($newpid = getmypid()) || !file_put_contents($runfile,$newpid)){ return; } while(true){ //收到結束進程新號,結束進程,並刪除相關檔案 if(file_exists($diefile) && unlink($runfile) && unlink($diefile)){ return; } /*這裡是守護進程要做的事*/ file_put_contents($file,"I'm Runing Now".PHP_EOL,FILE_APPEND); /***********************/ touch($runfile); sleep(5); } }}start("test");
PHP寫守護進程時要注意幾點:
1.首先就是函數clearstatcache()函數那裡,查官方手冊可以知道該函數是清除檔案狀態緩衝的,當在一個指令碼中多次檢查同一個檔案的緩衝狀態時如果不用該函數就會出錯,受該函數影響的有:stat(), lstat(), file_exists(), is_writable(),is_readable(), is_executable(), is_file(), is_dir(), is_link(),filectime(), fileatime(), filemtime(), fileinode(), filegroup(),fileowner(), filesize(), filetype(), fileperms().
2.在多次運行該指令碼時,會在運行前進行檢測,上次執行迴圈的時間距離現在大於300s或者pid號不匹配都會重啟該進程(時間在每次執行迴圈式都要更新touch)。
3.自動重啟也用到了crontab的議程表,將該檔案添加入議程表:
crontab -e
#開啟議程表,inset模式
*/3 * * * * /usr/bin/php -f process.php
#每3分鐘執行一次,放置進程掛掉
這樣就基本ok了,要是有具體功能的話還需改動代碼。