php實現(xiàn)簡單的守護進程創(chuàng)建、開啟與關(guān)閉操作
本文實例講述了php實現(xiàn)簡單的守護進程創(chuàng)建、開啟與關(guān)閉操作。分享給大家供大家參考,具體如下:
前提要安裝有pcntl擴展,可通過php -m
查看是否安裝
<?php class Daemon { private $pidfile; function __construct() { $this->pidfile = dirname(__FILE__).'/daemontest.pid'; } private function startDeamon() { if (file_exists($this->pidfile)) { echo "The file $this->pidfile exists.\n"; exit(); } $pid = pcntl_fork(); if ($pid == -1) { die('could not fork'); } else if ($pid) { echo 'start ok'; exit($pid); } else { // we are the child file_put_contents($this->pidfile, getmypid()); return getmypid(); } } private function start(){ $pid = $this->startDeamon(); while (true) { file_put_contents(dirname(__FILE__).'/test.txt', date('Y-m-d H:i:s'), FILE_APPEND); sleep(2); } } private function stop(){ if (file_exists($this->pidfile)) { $pid = file_get_contents($this->pidfile); posix_kill($pid, 9); unlink($this->pidfile); } } public function run($argv) { if($argv[1] == 'start') { $this->start(); }else if($argv[1] == 'stop') { $this->stop(); }else{ echo 'param error'; } } } $deamon = new Daemon(); $deamon->run($argv);
啟動
php deamon.php start
關(guān)閉
php deamon.php stop
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP進程與線程操作技巧總結(jié)》、《PHP網(wǎng)絡編程技巧總結(jié)》、《PHP基本語法入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
thinkphp使用phpmailer發(fā)送郵件的方法
這篇文章主要介紹了thinkphp使用phpmailer發(fā)送郵件的方法,包含了配置發(fā)送郵件類、設(shè)置參數(shù)及發(fā)送郵件測試等的具體步驟,具有一定的實用價值,需要的朋友可以參考下2014-11-11Laravel框架中隊列和工作(Queues、Jobs)操作實例詳解
這篇文章主要介紹了Laravel框架中隊列和工作(Queues、Jobs)操作實例詳解,需要的朋友可以參考下2020-04-04