魏长东

weichangdong

东邪

php多进程code

看到一个大神写的php多进程的代码,自己稍作修改,放着以后备用。

插播一个nginx的配置,之前一直以为nginx不能直接返回状态码,需要借助lua来实现呢,原来nginx本身也是可以滴。

server {
    listen 81;
    server_name 127.0.0.1;
    access_log off;
    add_header Content-Type "application/json;charset=utf-8";
    return 200 '{"retcode":0}';
}

<?php
/*
可以用kill 命令杀死
*/
class ServerThread
{
	public $isMain = false; 
	public $idList =  Array();
	public $fornum = 0;
	public $updateTime = 0;
    public static $redis = null;
	public function StartThread($num)
	{
		if ($num <= 0)
		{
			return 0;
		}
		for($i = 0; $i<$num;$i++)
		{
			$id = pcntl_fork();
			if ($id == -1)
			{
				die("fork fail");
			}
			if ($id == 0)
			{
				$this->isMain = false;
				$this->CallBack();
				return 0;
			}
			if ($id > 0)
			{
				$this->isMain = true;
				$this->idList[$i] = $id;
				echo  "im ppid ".$id."\n";
			}
		}
	}

	public function WaitPid()
	{
		while(count($this->idList) > 0)
		{
			
			foreach($this->idList as $a=>$b)
			{
				$res = pcntl_waitpid($b,$status,WNOHANG);
				if ($res != 0)
				{
					unset($this->idList[$a]);	
				}
			}
			sleep(1);
		}
	}
    
    
    public function Run()
	{
		$this->StartThread(10);
		if ($this->isMain)
		{
			$this->WaitPid();
		}
	}

	public function CallBack()
	{
		$this->start();
		while(true)
		{
			$this->CheckUpdate();
			$this->ToDo();
			$this->getSleep();
		}
	}
    
    public function start()
	{
		self::connectRedis();
	}
    
    public function getSleep()
	{
		usleep(10);
	}
	public function ToDo()
    {
sleep(5);
        echo getmypid()."\n";
        //exit;
    }
    
    function  connectRedis()
    {
        if (self::$redis === null) {
            self::$redis = new redis;
            self::$redis->pconnect('127.0.0.1',6379);
            self::$redis->auth('wcd');
            self::$redis->select(1);
        }
    }
    public function CheckUpdate()
	{
		pcntl_signal_dispatch();
		$i = self::$redis->get("signo");
		if ($i == 15)
		{
		      $pid = getmypid();
			$this->WriteData($pid);
			print_r($pid." kill exit\n");
			exit;
		}
    }
    public function WriteData($pid)
    {
        echo $pid. " this is  log\n";
    }
     
}
pcntl_signal(SIGHUP,  "sig_handler");
pcntl_signal(SIGTERM, "sig_handler");
function conredis()
{
    $redis = new redis;
    $redis->pconnect('127.0.0.1',6379);
    $redis->auth('wcd');
    $redis->select(1);
    return $redis;
}

function sig_handler($signo)
{
    $redis = conredis();
	$redis->set("signo", $signo);
}

$service = new ServerThread();
$service->Run();
$redis = conredis();
$redis->del("signo");
$pid = getmypid();
echo  "===".$pid."\n";