守護進程(daemon)是一類在後臺運行的特殊進程,用於執行特定的系統任務。php
不少守護進程在系統引導的時候啓動,而且一直運行直到系統關閉。oop
守護進程一直在後臺運行,脫離終端運行的程序 獨立運行的守護進程ui
1 <?php 2 class myProcess 3 { 4 const UID = 80; 5 const GID = 80; 6 protected $loop = true; 7 protected $pidFile = "/tmp/myprocess.pid"; 8 //protected $data = "123132132\r\n"; 9 10 private function checkPidFile() 11 { 12 if(file_exists($this->pidFile)) 13 { 14 echo "daemon process is already runing.\n"; 15 exit(); 16 } 17 } 18 private function daemon() 19 { 20 21 $pid = pcntl_fork(); 22 if ($pid == -1) 23 { 24 exit("fork fail"); 25 }else if($pid == 0){ 26 $this->handler(); 27 }else{ 28 exit(); 29 } 30 } 31 32 private function handler() 33 { 34 posix_setsid(); 35 posix_setuid(self::UID); 36 posix_setgid(self::GID); 37 #fclose(STDIN); 38 #fclose(STDOUT); 39 #fclose(STDERR); 40 #$pid = posix_getpid 41 $pid = getmypid(); 42 file_put_contents($this->pidFile, $pid); #or die("open file fail"); 43 } 44 45 46 private function start() 47 { 48 pcntl_signal_dispatch(); 49 $this->checkPidFile(); 50 $this->daemon(); 51 while ($this->loop) { 52 $id = getmypid(); 53 //$f = fopen("/tmp/a.txt",a); 54 //fwrite($f,$this->data); 55 //file_put_contents("/tmp/".$id.".log","進程ID:$id 正常運行\r\n"); 56 sleep(1); 57 } 58 } 59 60 private function stop() 61 { 62 if (file_exists($this->pidFile)) { 63 $pid = file_get_contents($this->pidFile); 64 posix_kill($pid, SIGHUP); 65 unlink($this->pidFile); 66 echo "stop success....."; 67 }else{ 68 echo "stop fail, daemon process not is already runing"; 69 } 70 } 71 72 private function restart() 73 { 74 $this->stop(); 75 $this->start(); 76 } 77 78 public function reload() 79 { 80 // $this->loop = false; 81 // pcntl_signal_dispatch(); 82 // $this->loop = true; 83 // $this->start(); 84 } 85 86 public function main($argv) 87 { 88 switch ($argv[1]) { 89 case 'start': 90 $this->start(); 91 break; 92 case 'stop': 93 $this->stop(); 94 break; 95 case 'restart': 96 $this->restart(); 97 break; 98 case 'reload': 99 $this->reload(); 100 break; 101 default: 102 echo 'php process.php start | stop | restart | reload'; 103 exit; 104 } 105 } 106 107 } 108 109 $proce = new myProcess(); 110 $proce->main($argv);