function spawnDownloader($data) { function thread_shutdown() { posix_kill(posix_getpid(), SIGHUP); } if ($pid = pcntl_fork()) { return; } // spawn to child process fclose(STDIN); // close descriptors fclose(STDOUT); fclose(STDERR); register_shutdown_function('thread_shutdown'); // zombie-proof if (posix_setsid() < 0) { return; } // re-parent child to kernel if ($pid = pcntl_fork()) { return; } // now in daemonized downloader // download stuff return; }
/** * @return \Generator|void * @throws \Aurora\Console\Exception */ public function start() { if (0 < ($pid = pcntl_fork())) { return; } elseif (-1 == $pid) { throw new Exception("Unable to create daemon process"); } posix_setsid(); if (0 < ($pid = pcntl_fork())) { // 禁止进程重新打开控制终端 exit(0); } elseif (-1 == $pid) { throw new Exception("Unable to create the process of leaving the terminal"); } chdir('/'); umask(0); $user = $this->config->get('master_user', 'nobody'); $group = $this->config->get('master_user_group', ''); Posix::setUser($user, $group); $filename = $this->config->get('pid_file_save_path', '/var/run/aurora.pid'); if (!($fd = @fopen($filename, 'w+'))) { throw new Exception("PID file creation failed" . error_get_last()['message']); } elseif (!flock($fd, LOCK_EX | LOCK_NB)) { throw new Exception("Unable to lock the PID file"); } fwrite($fd, posix_getpid()); // $this->closeStdDescriptors(); call_user_func(yield, $this->config); flock($fd, LOCK_UN); fclose($fd); unlink($filename); exit(0); }
public static function daemon($nochdir = true, $noclose = true) { umask(0); $pid = pcntl_fork(); if ($pid > 0) { exit; } elseif ($pid < 0) { return false; } else { // nothing to do ... } $pid = pcntl_fork(); if ($pid > 0) { exit; } elseif ($pid < 0) { return false; } else { // nothing to do ... } $sid = posix_setsid(); if ($sid < 0) { return false; } if (!$nochdir) { chdir('/'); } umask(0); if (!$noclose) { fclose(STDIN); fclose(STDOUT); fclose(STDERR); } return true; }
public function daemonize() { global $stdin, $stdout, $stderr; global $argv; set_time_limit(0); if (php_sapi_name() != "cli") { die("only run in command line mode\n"); } if ($this->is_sington == true) { $this->pid_file = $this->info_dir . "/" . __CLASS__ . "_" . substr(basename($argv[0]), 0, -4) . ".pid"; $this->checkPidfile(); } umask(0); if (pcntl_fork() != 0) { exit; } posix_setsid(); if (pcntl_fork() != 0) { exit; } chdir("/"); $this->setUser($this->user) or die("cannot change owner"); fclose(STDIN); fclose(STDOUT); fclose(STDERR); $stdin = fopen($this->output, 'r'); $stdout = fopen($this->output, 'a'); $stderr = fopen($this->output, 'a'); if ($this->is_sington == true) { $this->createPidfile(); } }
/** * Daemonize the current process so it can run in the background. * * If $pidfile is supplied, the process ID is written there. * Provide absolute path names for the parameters to avoid file not found errors or logs inside the source code folder. * * If an error occurred, a RuntimeException is thrown. * * @param string $pidfile File to write the process ID of the daemon to * @param string $stderr File to redirect STDERR to * @param string $stdout File to redirect STDOUT to * @param string $stdin File to read STDIN from * @throws \RuntimeException * @return true */ public static function daemonize($pidfile = null, $stderr = '/dev/null', $stdout = '/dev/null', $stdin = '/dev/null') { // Allow only cli scripts to daemonize, otherwise you may confuse your webserver if (\php_sapi_name() !== 'cli') { throw new \RuntimeException('Can only daemonize a CLI process!'); } self::checkPID($pidfile); self::reopenFDs($stdin, $stdout, $stderr); if (($pid1 = @\pcntl_fork()) < 0) { throw new \RuntimeException('Failed to fork, reason: "' . \pcntl_strerror(\pcntl_get_last_error()) . '"'); } elseif ($pid1 > 0) { exit; } if (@posix_setsid() === -1) { throw new \RuntimeException('Failed to become session leader, reason: "' . \posix_strerror(\posix_get_last_error()) . '"'); } if (($pid2 = @\pcntl_fork()) < 0) { throw new \RuntimeException('Failed to fork, reason: "' . \pcntl_strerror(\pcntl_get_last_error()) . '"'); } elseif ($pid2 > 0) { exit; } chdir('/'); umask(022); self::writePID($pidfile); return true; }
protected function forkChild($type) { $this->logger->error("Fork child process"); $pid = pcntl_fork(); if ($pid == -1) { // Cannot fork child throw new Scalr_System_Ipc_Exception("Cannot fork child process"); } else { if ($pid) { // Current process $this->shm->put($type, $pid); $this->logger->error(sprintf("Child PID: %s was forked", $pid)); } else { if (posix_getpid() == $this->shm->get($type)) { $this->logger->error("Detaching process from terminatal"); if (posix_setsid() == -1) { throw new Scalr_System_Ipc_Exception("Cannot detach process from terminal"); } } if ($type == self::GEARMAN_CLIENT) { $client = new Scalr_Service_Gearman_Client($this->servers); $client->mainLoop(); } elseif ($type == self::GEARMAN_WORKER) { $worker = new Scalr_Service_Gearman_Worker($this->servers); $worker->mainLoop(); } exit; } } }
/** * @param InputInterface $input * @param OutputInterface $output * @return int */ protected function execute(InputInterface $input, OutputInterface $output) { $config = (new ConfigLoader())->load(); // Create the child process // All the code after pcntl_fork () will be performed by two processes: parent and child if ($config->getItem('config', 'daemon', false)) { $child_pid = pcntl_fork(); if ($child_pid) { // Exit from the parent process that is bound to the console exit; } // Make the child as the main process. posix_setsid(); } $math = Bitcoin::getMath(); $params = new Params($math); $loop = \React\EventLoop\Factory::create(); $db = new DebugDb(Db::create($config)); $node = new BitcoinNode($config, $params, $db); $container = new Container(); $container['debug'] = function (Container $c) use($node) { $context = $c['zmq']; return new ZmqDebug($node, $context); }; $this->setupServices($container, $node, $loop, $config, $db); $loop->run(); return 0; }
/** * Create a daemon process. * * @return DaemonHttpApplication Return self to support chaining. */ public function execute() { // Create first child. if (pcntl_fork()) { // I'm the parent // Protect against Zombie children pcntl_wait($status); exit; } // Make first child as session leader. posix_setsid(); // Create second child. $pid = pcntl_fork(); if ($pid) { // If pid not 0, means this process is parent, close it. $this->processId = $pid; $this->storeProcessId(); exit; } $this->addLog('Daemonized'); fwrite(STDOUT, "Daemon Start\n-----------------------------------------\n"); $this->registerSignalHandler(); // Declare ticks to start signal monitoring. When you declare ticks, PCNTL will monitor // incoming signals after each tick and call the relevant signal handler automatically. declare (ticks=1); while (true) { $this->doExecute(); sleep(1); } return $this; }
private function detach() { $rv = posix_setsid(); if ($rv === -1) { Log::error("detach failed"); die; } }
/** * @throws \RuntimeException */ public final function detach() { if (-1 === posix_setsid()) { throw new \RuntimeException("Unable to detach thread"); } $this->pid = posix_getpid(); $this->parentPid = null; $this->detached = true; }
function daemon() { if (pcntl_fork() != 0) { exit; } posix_setsid(); if (pcntl_fork() != 0) { exit; } pcntl_signal(SIGTERM, "handler"); }
function UMDDaemon($sockaddr) { $this->sockaddr = $sockaddr; $this->openlog('/tmp/umd' . basename($sockaddr) . '.log'); unlink($this->sockaddr); $this->file = __FILE__; $listen = socket_create(AF_UNIX, SOCK_STREAM, 0) or die('Cannot create socket'); socket_bind($listen, $this->sockaddr) or die('Cannot bind'); socket_listen($listen) or die('Cannot listen'); $this->register_listener($listen); posix_setsid(); }
/** * 初始化守护进程 * */ private static function demonize() { php_sapi_name() != 'cli' && die('should run in cli'); umask(0); $pid = pcntl_fork(); if ($pid < 0) { die("can't Fork!"); } else { if ($pid > 0) { exit; } } if (posix_setsid() === -1) { //使进程成为会话组长。让进程摆脱原会话的控制;让进程摆脱原进程组的控制; die('could not detach'); } $pid = pcntl_fork(); if ($pid === -1) { die("can't fork2!"); } elseif ($pid > 0) { self::message('start success!'); exit; } defined('STDIN') && fclose(STDIN); defined('STDOUT') && fclose(STDOUT); defined('STDERR') && fclose(STDERR); $stdin = fopen(self::$log, 'r'); $stdout = fopen(self::$log, 'a'); $stderr = fopen(self::$log, 'a'); self::setUser(self::$user); file_put_contents(self::$pidFile, posix_getpid()) || die("can't create pid file"); self::setProcessName('master'); pcntl_signal(SIGINT, array('\\' . __CLASS__, 'signalHandler'), false); pcntl_signal(SIGUSR1, array('\\' . __CLASS__, 'signalHandler'), false); file_put_contents(self::$status, '<?php return ' . var_export(array(), true) . ';', LOCK_EX); self::createChildrenProcess(); while (true) { pcntl_signal_dispatch(); $pid = pcntl_wait($status, WUNTRACED); pcntl_signal_dispatch(); if ($pid > 0) { $status = self::getStatus(); if (isset($status['pid'][$pid])) { unset($status['pid'][$pid]); file_put_contents(self::$status, '<?php return ' . var_export($status, true) . ';', LOCK_EX); } self::createChildrenProcess(); } sleep(1); } return; }
/** * 进程daemon化 * @return [type] [description] */ public static function daemonize() { // fork子进程,父进程退出 if (0 != pcntl_fork()) { exit; } // 设置当前进程为会话组长 posix_setsid(); // fork脱离终端 if (0 != pcntl_fork()) { exit; } }
protected function execute(InputInterface $input, OutputInterface $output) { $childPid = pcntl_fork(); if ($childPid) { $output->writeln('Creating of child fork has been succesfull finished with pid = ' . $childPid); exit; } posix_setsid(); $rabbitMQCommand = $this->getApplication()->find('rabbitmq:consumer'); $arguments = array('command' => 'rabbitmq:consumer', 'name' => 'push'); $input = new ArrayInput($arguments); $rabbitMQCommand->run($input, $output); }
function daemonize() { $child = pcntl_fork(); if ($child) { exit(0); // kill parent } posix_setsid(); // become session leader umask(0); // clear umask return posix_getpid(); }
/** * Daemonize a Closure object. * * @throws \Exception * * @param array $options Set of options * @param callable $callable Closure object to daemonize * * @return bool True on success, throws an Exception otherwise */ public static function work(array $options, callable $callable) { if (!extension_loaded('pcntl')) { throw new \Exception('pcntl extension required'); } if (!extension_loaded('posix')) { throw new \Exception('posix extension required'); } if (!isset($options['pid'])) { throw new \Exception('pid not specified'); } $options = $options + array('stdin' => '/dev/null', 'stdout' => '/dev/null', 'stderr' => 'php://stdout'); if (($lock = @fopen($options['pid'], 'c+')) === false) { throw new \Exception('unable to open pid file ' . $options['pid']); } if (!flock($lock, LOCK_EX | LOCK_NB)) { throw new \Exception('could not acquire lock for ' . $options['pid']); } switch ($pid = pcntl_fork()) { case -1: throw new \Exception('unable to fork'); case 0: break; default: fseek($lock, 0); ftruncate($lock, 0); fwrite($lock, $pid); fflush($lock); return; } if (posix_setsid() === -1) { throw new \Exception('failed to setsid'); } fclose(STDIN); fclose(STDOUT); fclose(STDERR); if (!($stdin = fopen($options['stdin'], 'r'))) { throw new \Exception('failed to open STDIN ' . $options['stdin']); } if (!($stdout = fopen($options['stdout'], 'w'))) { throw new \Exception('failed to open STDOUT ' . $options['stdout']); } if (!($stderr = fopen($options['stderr'], 'w'))) { throw new \Exception('failed to open STDERR ' . $options['stderr']); } pcntl_signal(SIGTSTP, SIG_IGN); pcntl_signal(SIGTTOU, SIG_IGN); pcntl_signal(SIGTTIN, SIG_IGN); pcntl_signal(SIGHUP, SIG_IGN); call_user_func($callable, $stdin, $stdout, $stderr); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { if (defined('HHVM_VERSION')) { $output->writeln('<error>This command is not supported on HHVM.</error>'); return 1; } if (!extension_loaded('pcntl')) { $output->writeln('<error>This command needs the pcntl extension to run.</error>'); $output->writeln('You can either install it or use the <info>server:run</info> command instead to run the built-in web server.'); return 1; } $env = $this->getContainer()->getParameter('kernel.environment'); if ('prod' === $env) { $output->writeln('<error>Running PHP built-in server in production environment is NOT recommended!</error>'); } $pid = pcntl_fork(); if ($pid < 0) { $output->writeln('<error>Unable to start the server process</error>'); return 1; } $address = $input->getArgument('address'); if ($pid > 0) { $output->writeln(sprintf('<info>Web server listening on http://%s</info>', $address)); return; } if (posix_setsid() < 0) { $output->writeln('<error>Unable to set the child process as session leader</error>'); return 1; } if (null === ($process = $this->createServerProcess($output, $address, $input->getOption('docroot'), $input->getOption('router'), $env, null))) { return 1; } $process->disableOutput(); $process->start(); $lockFile = $this->getLockFile($address); touch($lockFile); if (!$process->isRunning()) { $output->writeln('<error>Unable to start the server process</error>'); unlink($lockFile); return 1; } // stop the web server when the lock file is removed while ($process->isRunning()) { if (!file_exists($lockFile)) { $process->stop(); } sleep(1); } }
function deamonlize() { $pid = pcntl_fork(); if ($pid < 0) { cy_log(CYE_ERROR, "pcntl_fork({$key}) error."); exit(-1); } if ($pid > 0) { exit(0); } $d = posix_setsid(); fclose(STDIN); fclose(STDOUT); fclose(STDERR); }
/** * 摆脱终端,使进程成为新的会话组长 */ function daemon() { $pid = pcntl_fork(); if ($pid == -1) { die("fork failed for daemon"); } else { if ($pid) { exit; } else { //摆脱终端,使进程成为新的会话组长 if (posix_setsid() == -1) { die("could not detach from terminal"); } } } }
public function setUp() { // Make this process a session leader so we can send signals // to this job as a whole (including any subprocesses such as spawned by Symfony). posix_setsid(); if (function_exists('pcntl_alarm') && function_exists('pcntl_signal')) { if (!empty($this->args['sigFile'])) { echo sprintf('[-] Signal file requested, polling "%s".' . PHP_EOL, $this->args['sigFile']); declare (ticks=1); pcntl_signal(SIGALRM, [$this, 'alarmHandler']); pcntl_alarm(1); } } $this->updateStatus(DNDeployment::TR_DEPLOY); chdir(BASE_PATH); }
public function init() { declare (ticks=1); gc_enable(); $pid_h = $this->open_pid_file($this->pid_file); error_reporting(0); ini_set("max_execution_time", "0"); ini_set("max_input_time", "0"); set_time_limit(0); ob_implicit_flush(); pcntl_signal(SIGCHLD, "sig_handler"); pcntl_signal(SIGKILL, "sig_handler"); pcntl_signal(SIGTERM, "sig_handler"); pcntl_signal(SIGINT, "sig_handler"); pcntl_signal(SIGQUIT, "sig_handler"); pcntl_signal(SIGSTOP, "sig_handler"); $pid = pcntl_fork(); if ($pid === -1) { die('Could not fork!'); } elseif ($pid) { // this is the parent process exit; } else { // this is the child process chdir("/"); umask(0); // reopen standard file descriptors // this is necessary to decouple the daemon from the TTY fclose(STDIN); fclose(STDOUT); fclose(STDERR); $STDIN = fopen('/dev/null', 'r'); $STDOUT = fopen('/dev/null', 'wb'); $STDERR = fopen('/dev/null', 'wb'); // make it session leader posix_setsid(); chdir("/"); umask(0); $pid_id = posix_getpid(); pcntl_signal(SIGCHLD, "signal_handler"); pcntl_signal(SIGTERM, "signal_handler"); pcntl_signal(SIGINT, "signal_handler"); fputs($pid_h, $pid_id); fclose($pid_h); $this->write_log_file($this->daemon_name . " started"); } }
private function start() { if ($this->daemonize) { $pid = pcntl_fork(); switch ($pid) { case -1: //error echo "fork error\n"; return; case 0: //child $sid = posix_setsid(); if ($sid < 0) { echo "setsid error\n"; return; } global $STDOUT, $STDERR; fclose(STDOUT); fclose(STDERR); $STDOUT = fopen('/dev/null', "rw+"); $STDERR = fopen('/dev/null', "rw+"); break; default: //master exit(0); } } file_put_contents($this->pidfile, getmypid()); $this->setupSignal(); $this->runDaemon(); $last = 0; do { $now = time(); if ($last != $now) { $last = $now; $this->runCrontab(); sleep(1); } else { $ms = 1000 - (int) ((microtime(true) - $now) * 1000); usleep($ms * 1000); } pcntl_signal_dispatch(); } while (true); unlink($this->pidfile); }
public function executePre(InputInterface $input) { $this->log = new Logger('application'); $this->log->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG)); $this->log->pushHandler(new StreamHandler('log/application.log', Logger::DEBUG)); if ($input->hasOption('shutdown') && $input->getOption('shutdown')) { if (file_exists($this->getPidfilePath())) { $pid = file_get_contents($this->getPidfilePath()); $this->log->info('kill ' . $pid); posix_kill($pid, SIGTERM); } exit; } elseif ($input->hasOption('daemon') && $input->getOption('daemon')) { #$this->log->info('daemon'); if (function_exists('pcntl_fork')) { #$this->log->info('fork'); $pid = pcntl_fork(); if ($pid < 0 || $pid) { #$this->log->info('fork exit: '.$pid); exit; } #$this->log->info('fork ok: '.$pid); #$this->log->info('setsid'); $sid = posix_setsid(); #$this->log->info('sid: '.$sid); #$this->log->info('ignore signals'); $this->signalHandlerSetup(); $pid = pcntl_fork(); if ($pid < 0 || $pid) { #$this->log->info('fork again exit: '.$pid); exit; } #$this->log->info('fork again ok: '.$pid); umask(0); $this->stdStreamsSetup(); } } else { $this->signalHandlerSetup(); } $this->pidFile = new PidFile(new ProcessManager(), $this->getPidfilePath()); $this->pidFile->acquireLock(); $this->pidFile->setPid(getmypid()); }
public function init() { $pid = pcntl_fork(); if ($pid == -1) { //Return message for the //echo json_encode(array('ERROR' => 1, 'MESSAGE' => 'CANNOT FORK, check php configuration', 'CODE_ERROR' => ERROR_FORK)); exit(1); } elseif ($pid) { //echo json_encode(array('PID' => $pid, 'ERROR' => 0, 'MESSAGE' => 'Running tasks...', 'PROGRESS' => 0)); exit(0); } else { //Daemonize the element $this->father_pid = posix_getppid(); $sid = posix_setsid(); $this->pid = getmypid(); echo $this->father_pid; $this->log(array('ERROR' => 0, 'MESSAGE' => 'Running daemon...', 'PROGRESS' => 0)); } }
public function daemonize() { global $stdin, $stdout, $stderr; global $argv; \set_time_limit(0); // 只允许在cli下面运行 if (\php_sapi_name() != "cli") { die("only run in command line mode\n"); } // 只能单例运行 if ($this->is_sington == true) { $this->pid_file = $this->info_dir . "/" . __CLASS__ . "_" . \substr(\basename($argv[0]), 0, -4) . ".pid"; $this->check_pid_file(); } \umask(0); //把文件掩码清0 if (\pcntl_fork() != 0) { //是父进程,父进程退出 exit; } \posix_setsid(); //设置新会话组长,脱离终端 if (\pcntl_fork() != 0) { //是第一子进程,结束第一子进程 exit; } \chdir("/"); //改变工作目录 $this->set_user($this->user) or die("cannot change owner"); //关闭打开的文件描述符 \fclose(STDIN); \fclose(STDOUT); \fclose(STDERR); $stdin = \fopen($this->output, 'r'); $stdout = \fopen($this->output, 'a'); $stderr = \fopen($this->output, 'a'); if ($this->is_sington == true) { $this->create_pid_file(); } \pcntl_signal(SIGTERM, SIG_DFL); \pcntl_signal(SIGINT, SIG_DFL); \pcntl_signal(SIGQUIT, SIG_DFL); }
/** * Create a daemon process. * * @return DaemonHttpApplication Return self to support chaining. */ public function execute() { // Create first child. if (pcntl_fork()) { // I'm the parent // Protect against Zombie children pcntl_wait($status); exit; } // Make first child as session leader. posix_setsid(); // Create second child. if (pcntl_fork()) { // If pid not 0, means this process is parent, close it. exit; } // Create Http server $this->createHttpServer(); return $this; }
private function runnize() { if ($this->isRunning()) { // is already running. Exiting return false; } if (!$this->fork()) { // Coudn't fork. Exiting. return false; } if (!posix_setsid()) { // $this->_logMessage('Could not make the current process a session leader', DLOG_ERROR); return false; } declare (ticks=1); pcntl_signal(SIGCHLD, array($this, 'sigHandler')); pcntl_signal(SIGTERM, array($this, 'sigHandler')); pcntl_signal(SIGHUP, array($this, 'sigHandler')); return true; }
function daemonize() { $pid = pcntl_fork(); if ($pid == -1) { die("fork(1) failed!\n"); } elseif ($pid > 0) { //让由用户启动的进程退出 exit(0); } //建立一个有别于终端的新session以脱离终端 posix_setsid(); //此时子进程已经成为无控制终端的会话组长进程,但有可能再次打开一个控制终端;再次fork,变成非会话组长进程即可。 $pid = pcntl_fork(); if ($pid == -1) { die("fork(2) failed!\n"); } elseif ($pid > 0) { //父进程退出, 剩下子进程成为最终的独立进程 exit(0); } }
/** * Detaches process from console and starts forking. * * Requires php-posix! * * @see self::start() */ public final function startDetached() { // Forking one child process and closing the parent, // because if the parent is already a session leader, it cannot leave it. // It is because session group an dprocess group has the same ID as their // leader process. Now if you assign the leader process to another // session/process group, the IDs will collide. $pid = $this->fork(); if ($pid > 0) { // We are in the parent, so we terminate. exit(0); } // Becoming leader of a new session/process group - detaching from shell. $sid = posix_setsid(); if (false === $sid) { throw new PHPTracker_Concurrency_Error('Unable to become session leader (detaching).'); } // We have to handle hangup signals (send when session leader terminates), otherwise it makes child process to stop. pcntl_signal(SIGHUP, SIG_IGN); // Forking again for not being session/process group leaders will disallow the process // to "accidentally" open a controlling terminal for itself (System V OSs). $pid = $this->fork(); if ($pid > 0) { // We are in the parent, so we terminate. exit(0); } // Releasing current directory and closing open file descriptors (standard IO). chdir('/'); fclose(STDIN); fclose(STDOUT); // PHP still thinks we are a webpage, and since we closed standard output, // whenever we echo, it will assume that the client abandoned the connection, // so it silently stops running. // We can tell it here not to do it. ignore_user_abort(true); // Let the world know about our process ID in a standard way. file_put_contents('/var/run/phptracker', getmypid()); // Finally we start the procedure as we would without detaching. $arguments = func_get_args(); return call_user_func_array(array($this, 'start'), $arguments); }