php进程管理
2016-07-15 18:35
483 查看
<?php /** * Created by PhpStorm. * User: * Date: 2016/7/15 * Time: 16:38 */ class ChildWork{ function run(){ while(true){ sleep(5); file_put_contents('work.log',date("y-m-d H:i:s" ,time()) ."\n" ,FILE_APPEND) ; } } } class work{ public $pidNum = 1; // 开放进程数目 public $path = __DIR__ ; // public $chlidWork = Null; public $pidFileList = []; public function __construct($pidNum , $childInstance){ $this->pidNum = $pidNum ; $this->chlidWork = $childInstance ; $this->path = $this->path .'/pid'; if(!file_exists($this->path)){ mkdir($this->path,0777); } } /** * @author */ function start(){ if($this->pidNum > 1) { for($i = 0; $i < $this->pidNum; ++$i) { $pid = $this->fork(); if($pid == -1) { die(); } // Child, start the worker else if(!$pid) { $this->chlidWork->run(); } } } } /** * @author */ function background(){ $sid = posix_setsid();//设置新会话组长,脱离终端 echo 'childen *****' .posix_getppid()."\n"; if ($sid < 0) exit; } /** * 守护进程 * @author */ function daemon(){ if($this->pidNum > 1) { for($i = 0; $i < $this->pidNum; ++$i) { $pid = $this->fork(); if($pid == -1) { die(); } // Child, start the worker else if(!$pid) { $this->pidFileList[$i] = $this->path.'/'.getmypid().'.pid'; file_put_contents ($this->pidFileList[$i], getmypid()); $sid = posix_setsid();//设置新会话组长,脱离终端 file_put_contents('daemon.log',json_encode($this->pidFileList)); $this->chlidWork->run(); 10b6e } } } } /** * fork 子进程 * @return int * @author */ function fork(){ if(!function_exists('pcntl_fork')) { return -1; } $pid = pcntl_fork(); if($pid === -1) { exit; } return $pid; } function stop(){ $dir = $this->path; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if($file =='.' || $file =='..') continue; $pidFile= $this->path.'/'.$file ; $pid = file_get_contents($pidFile); posix_kill($pid, 9); unlink($pidFile); } closedir($dh); } } } private function help($proc){ printf("%s start | stop | help \n", $proc); } function main($argv){ if($argv[1] === 'stop'){ $this->stop(); }else if($argv[1] === 'start'){ $this->start(); }else if($argv[1] === 'restart'){ $this->stop(); $this->start(); }else if($argv[1] === 'status'){ // $this->status(); }else if($argv[1] === 'daemon'){ $this->daemon(); }else if($argv[1] === 'reload'){ // $this->reload(); }else{ $this->help($argv[0]); } } } $work = new work(2,new ChildWork()); $work->main($argv);
相关文章推荐
- PHP下載網址
- 【php:thinkphp 】URL重定向
- Yii调试查看执行SQL语句的方法
- CodeIgniter框架源码笔记(5)——识别多种URI风格:地址解析类URI.php
- **PHP** 表单(2)-表单完成
- PHP中FTP相关函数小结
- 【旧代码整理】分享带cookie的PHP Curl操作class,再简单说说curl配合socks5代理、IP变身
- YII做项目问题汇总<一>
- php中三元运算符用法($c=$a>$b?($a-$b):($a+$b);)
- php数组和对象相互转换
- windows下的PHP环境配置
- Zend Studio导致PHP插入数据库中文乱码【坑了个爹】
- Yii数据模型中rules类验证器用法分析
- ubuntu14.04 搭建ftp
- Yii控制器中filter过滤器用法分析
- 一次PHP代码上线遇到的问题
- 一个高级PHP工程师所应该具备的条件
- Yii(2)读写分离配置
- thinkphp学习_第二天
- **PHP** 表单(1)-表单处理