《PHP編程:PHP進程同步代碼實例》要點:
本文介紹了PHP編程:PHP進程同步代碼實例,希望對您有用。如果有疑問,可以聯系我們。
經常遇到這樣一種情況,計劃任務定時后臺執行某個php程序,有時候也必要手動執行,可能多個人都必要執行這個程序,如果任務持續時間非常長,就很容易造成重復執行,所以就開發了下面的類.PHP實例
作用:在實際代碼運行前檢查與當前相同操作的進程是否正在運行,高并發運行是可靠的,運行中的進程中途異常中斷不會發生任何影響.PHP實例
構造辦法傳遞pid文件目錄的絕對路徑,需要自己保證不同進程對應不同pid文件.PHP實例
/*
?* 同一個PHP進程只運行一次,根據進程名字判斷是否為排重進程,只能運行于linux,高并發條件下是并發平安的.
?*/PHP實例
class SyncProcess {PHP實例
?private $pidFile;PHP實例
?function __construct($pidFile) {
??$this->pidFile = $pidFile;
?}PHP實例
?/**
? * 非阻塞方式返回過程是否正在運行
? */
?function check() {
??if (PHP_OS == 'Linux') {
???$pidFile = $this->pidFile;
???if (!empty($pidFile)) {
????$flag = false;
????$pidDir = dirname($pidFile);
????if (is_dir($pidDir)) {
?????$flag = true;
????}
????if ($flag) {
?????$running = true;
?????clearstatcache(true, $this->pidFile);
?????if (!file_exists($this->pidFile))
??????file_put_contents($this->pidFile, '', LOCK_EX);
?????$f = fopen($this->pidFile, 'r+');
?????if (flock($f, LOCK_EX ^ LOCK_NB)) {
??????$pid = trim(fgets($f));
??????if (!$this->is_process_running($pid)) {
???????$running = false;
??????}
?????}
?????if (!$running) {
??????fseek($f, 0);
??????ftruncate($f, 0);
??????fwrite($f, getmypid());
?????}
?????flock($f, LOCK_UN);
?????fclose($f);
?????return $running;
????} else {
?????debug_print("pid file($pidFile) is invalid", E_USER_WARNING);
????}
???} else {
????debug_print("pid file cant't be empty", E_USER_WARNING);
???}
??} else {
???debug_print(__CLASS__ . ' can only run in Linux', E_USER_WARNING);
???return true;
??}
?}PHP實例
?/**
? * 如果正在運行或者發生未知差錯返回true,如果沒有運行返回false
? * @param mixed $pid
? */
?private function is_process_running($pid) {
??if (is_numeric($pid) && $pid > 0) {
???$output = array();
???$line = exec("ps -o pid --no-headers -p $pid", $output);
???//返回值有空格
???$line = trim($line);
???if ($line == $pid) {
????return true;
???} else {
????if (empty($output)) {
?????return false;
????} else {
?????if (php_sapi_name() == 'cli')
??????$n = "\n";
?????else
??????$n = "<br>";
?????//到這一步的話應該是出什么問題了
?????$output = implode($n, $output);
?????debug_print($output, E_USER_WARNING);
?????return true;
????}
???}
??}else {
???return false;
??}
?}PHP實例
}
PHP實例
Demo:PHP實例
歡迎參與《PHP編程:PHP進程同步代碼實例》討論,分享您的想法,維易PHP學院為您提供專業教程。