您的位置:首页 > 编程语言 > PHP开发

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: