123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- <?php
- /**
- * Created by PhpStorm.
- * User: stanley-king
- * Date: 2018/7/28
- * Time: 下午12:49
- */
- namespace event;
- use Log;
- class util
- {
- static public function listen($host,$port)
- {
- $listen_fd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
- if(!socket_set_option($listen_fd, SOL_SOCKET, SO_REUSEADDR, 1)) {
- Log::record("socket_set_option 地址重用失败.",Log::DEBUG);
- return false;
- }
- if(!socket_set_nonblock($listen_fd)) {
- $err = socket_last_error();
- Log::record("socket_set_blocking error : {$err}",Log::DEBUG);
- return false;
- }
- if(!socket_bind($listen_fd, $host, $port)) {
- echo "无法绑定socket {$host} : {$port},请退出之前进程.\n";
- return false;
- }
- if(!socket_listen($listen_fd)) {
- echo "无法监听socket,请退出之前进程.\n";
- return false;
- }
- return $listen_fd;
- }
- static function fork_child($callback, $params)
- {
- if (($pid = pcntl_fork()) === 0)
- {
- //ob_end_clean(); // Discard the output buffer and close
- fclose(STDIN); // Close all of the standard
- fclose(STDOUT); // file descriptors as we
- fclose(STDERR); // are running as a daemon.
- Log::record("pcntl_fork pid = {$pid}",Log::DEBUG);
- if(!empty($params)) {
- call_user_func_array($callback,$params);
- } else {
- call_user_func($callback);
- }
- exit();
- }
- elseif($pid === -1)
- {
- Log::record("pid = {$pid},could not fork process",Log::DEBUG);
- die('could not fork process');
- }
- else
- {
- $ret = pcntl_waitpid($pid,$status,WNOHANG);
- Log::record("pcntl_waitpid pid = {$pid}",Log::DEBUG);
- if($ret == 0) {
- Log::record("spawn-fcgi: successful ret == 0 PID: {$pid}",Log::DEBUG);
- }
- elseif($ret == -1) {
- Log::record("spawn-fcgi: ret == -1 PID: {$pid}",Log::DEBUG);
- }
- else {
- Log::record("spawn-fcgi: ret == 0 child exited PID: {$pid}.",Log::DEBUG);
- }
- }
- }
- static function fork_listen($host, $port, $callback, $count)
- {
- $fd = util::listen($host,$port);
- if($fd === false) {
- Log::record("cannot open listen socket = {$host}:{$port}",Log::DEBUG);
- return false;
- }
- $params = [$fd];
- $count = intval($count);
- if($count <= 0) {
- return call_user_func_array($callback,$params);
- }
- else
- {
- while ($count--) {
- util::fork_child($callback,$params);
- }
- socket_close($fd);
- }
- }
- static function fork_worker($callback, $count)
- {
- $count = intval($count);
- if($count <= 0) {
- return call_user_func($callback);
- }
- else
- {
- while ($count--) {
- util::fork_child($callback,NULL);
- }
- }
- }
- }
|