跳至
[1]
[全屏预览]
pidfile = __dir__ . '/' . self::pidname . '.pid';
}
/**
* @return int
*/
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
exit($pid);
} else {
// we are the child
file_put_contents($this->pidfile, getmypid());
posix_setuid(self::uid);
posix_setgid(self::gid);
cli_set_process_title(self::process_name);
pcntl_signal(sighup, [$this, 'signoh']);
pcntl_signal(sigterm, [$this, 'signoh']);
pcntl_signal(sigchld, [$this, 'signoh']);
pcntl_signal(sigquit, [$this, 'signoh']);
pcntl_signal(sigint, [$this, 'signoh']);
pcntl_signal(sigusr1, [$this, 'signoh']);
return (getmypid());
}
}
/**
*
*/
private function run() {
do {
pcntl_signal_dispatch();
if ($this->stop) {
break;
}
echo "i am alive" . mt_rand(0,20) . "...\n";
sleep(5);
} while (true);
echo ("进程退出\n");
}
public function restart() {
$this->stop();
$this->start();
print "重启成功!\n";
}
/**
*
*/
private function start() {
$pid = $this->daemon();
$this->run();
}
/**
*
*/
private function stop() {
if (file_exists($this->pidfile)) {
$pid = file_get_contents($this->pidfile);
posix_kill($pid, sigkill);
unlink($this->pidfile);
}
}
/**
* @param $proc
*/
private function help($proc) {
printf("%s start | stop | restart | stat | help \n", $proc);
}
/**
* @param $argv
*/
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 if ($argv[1] === 'restart') {
$this->restart();
} else if ($argv[1] === 'stat') {
if (is_file($this->pidfile)) {
posix_kill(file_get_contents($this->pidfile), sighup);
} else {
print "\n_______程序没有启动________\n";
}
} else {
$this->help("command list :");
}
}
/**
* @param $instance
* @param $channelname
* @param $message
*/
public function handle($instance, $channelname, $message) {
file_put_contents(__dir__ . "/$channelname.txt", $message . "\n", file_append);
}
/**
* @param $signo
*/
public function signoh($signo) {
switch ($signo) {
case sighup :
print "\n___________运行状态___________\n";
print "host :" . self::host . "\n";
print "port :" . self::port . "\n";
print "name : " . self::process_name . "\n";
print "pid : " . file_get_contents($this->pidfile) . "\n";
print "________________________________\n";
break;
case sigterm:
posix_kill(file_get_contents($this->pidfile), 9);
break;
default :
print "\n________________________________\n";
print "呀!~有人想杀掉我!\n";
print "________________________________\n";
}
}
}