<?php
define("APPLICATION_PATH", realpath(dirname(__FILE__) . '/../../../')); //指向public的上一级
require APPLICATION_PATH . '/scripts/crontab/baseCli.php';
require APPLICATION_PATH . '/scripts/crontab/common.php';
error_reporting(E_ALL ^ E_NOTICE);
class runRedisPush
{
    /* config */
    const LISTEN = "tcp://192.168.2.15:5555";
    const MAXCONN = 100;
    const pidfile = __CLASS__;
    const uid = 80;
    const gid = 80;
    /**/
    protected $pool = NULL;
    protected $zmq = NULL;

    public function __construct()
    {
        $this->pidfile = '/var/run/' . self::pidfile . '.pid';
    }

    private function daemon()
    {
        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) {
// we are the parent
//pcntl_wait($status); //Protect against Zombie children
            exit($pid);
        } else {
// we are the child
            file_put_contents($this->pidfile, getmypid());
            posix_setuid(self::uid);
            posix_setgid(self::gid);
            return (getmypid());
        }
    }

    private function start()
    {
        $pid = $this->daemon();
        $conf = \Yaf\Registry::get('config')->get('redis.database.params');
        $redis=new Redis();
        $redis->connect($conf['host'], $conf['port']);
        if(!empty($conf['password'])){
            $redis->auth($conf['password']);
        }
//ini_set('default_socket_timeout', -1);(所有长连接不超时)
        $redis->setOption(Redis::OPT_READ_TIMEOUT, -1);
        $result=$redis->subscribe(array('redisPublish'), 'callback');
        function printTest($meg){
            echo $meg.'213';
        }
        function callback($instance,$channelName,$message){
            printTest($message);
        }
    }

    private function stop()
    {

        if (file_exists($this->pidfile)) {
            $pid = file_get_contents($this->pidfile);
            posix_kill($pid, 9);
            unlink($this->pidfile);
        }
    }

    private function help($proc)
    {
        printf("%s start | stop | help \n", $proc);
    }

    public function main($argv)
    {
        if (count($argv) < 2) {
            printf("please input help parameter\n");
            exit();
        }
        if ($argv[1] === 'stop') {

            $this->stop();
        } else if ($argv[1] === 'start') {
            $this->start();
        } else {
            $this->help($argv[0]);
        }
    }
}

$cgse = new runRedisPush();
$cgse->main($argv);