/** * Creates a lock file for the given name. * * @param string $name The name of this lock file * @param bool $check If we should check if the process exists in addition to check for a lock file * @return boolean */ public static function acquire($name, $check = false) { $pid = self::getProcessID($name); if (!empty($pid)) { // Test asks us to check if the process is still running if ($check) { if (function_exists('posix_kill')) { $exists = posix_kill($pid, 0); } else { $retval = 0; $out = array(); exec('kill -s 0 ' . $pid, $out, $retval); $exists = $retval == 0; } if ($exists) { return false; } } return false; } // create the pid file $fp = fopen(self::getProcessFilename($name), 'w'); flock($fp, LOCK_EX); fwrite($fp, getmypid()); flock($fp, LOCK_UN); fclose($fp); return true; }
private function CheckDaemon() { if ($pidfile = @fopen($this->pidfile_path, "r")) { $pid_daemon = fgets($pidfile, 20); fclose($pidfile); $pid_daemon = (int) $pid_daemon; // bad PID file, e.g. due to system malfunction while creating the file? if ($pid_daemon <= 0) { echo "removing bad pid_file (" . $this->pidfile_path . ")\n"; unlink($this->pidfile_path); return false; } elseif (posix_kill($pid_daemon, 0)) { // yes, good bye echo "Error: process for " . $this->pidfile_path . " is already running with pid={$pid_daemon}\n"; return false; } else { // no, remove pid_file echo "process not running, removing old pid_file (" . $this->pidfile_path . ")\n"; unlink($this->pidfile_path); return true; } } else { return true; } }
/** * 多进程处理任务 * @param callback $mission_func 子进程要进行的任务函数 */ public function dealMission($mission_func) { $this->_mission_func = $mission_func; for ($i = 0; $i < $this->_process_num; $i++) { $pid[] = pcntl_fork(); if ($pid[$i] == 0) { //等于0时,是子进程 $this->_func_obj->{$mission_func}($i + 1); //结束当前子进程,以防止生成僵尸进程 if (function_exists("posix_kill")) { posix_kill(getmypid(), SIGTERM); } else { system('kill -9' . getmypid()); } exit; } else { if ($pid > 0) { //大于0时,是父进程,并且pid是产生的子进程的PID //TODO 可以记录下子进程的pid,用pcntl_wait_pid()去等待程序并结束 pcntl_wait($status); } else { throw new Exception('fork fail'); } } } }
public function stopDownload() { $wget_pid = $this->_get_wget_pid($_localImagePath); if ($wget_pid != -1) { posix_kill($wget_pid, SIGKILL); } }
/** * Kills all running child-processes */ public function killChildProcesses() { $child_pids = $this->getChildPIDs(); for ($x = 0; $x < count($child_pids); $x++) { posix_kill($child_pids[$x], SIGKILL); } }
public final function execute() { $hasThreads = function_exists('pcntl_signal'); if (!$hasThreads || Cli::getInstance()->isSimulation()) { flush(); try { return $this->executeNoThread(); } catch (Interrupt $e) { throw $e; } catch (Exception $e) { echo $e; } return; } pcntl_signal(SIGCHLD, SIG_IGN); $pid = pcntl_fork(); if ($pid < 1) { $this->_run(); posix_kill(posix_getpid(), 9); pcntl_waitpid(posix_getpid(), $temp = 0, WNOHANG); pcntl_wifexited($temp); exit; //Make sure we exit... } else { $this->pid = $pid; } }
/** * @param string $pidPath * @param bool $throwException * @param LoggerInterface $logger * @param LOLClientInterface|null $client * * @throws \RuntimeException */ public static function killProcess($pidPath, $throwException, LoggerInterface $logger, LOLClientInterface $client = null) { $pid = (int) file_get_contents($pidPath); // Test if process is still running $output = []; exec('ps ' . $pid, $output); if (!isset($output[1])) { if (null != $client) { $logger->debug('Client ' . $client . ' (pid: #' . $pid . ') not running, deleting cache pid file'); } else { $logger->debug('Process #' . $pid . ' not running, deleting cache pid file'); } unlink($pidPath); return; } // Kill if (posix_kill($pid, SIGKILL)) { if (null != $client) { $logger->debug('Client ' . $client . ' (pid: #' . $pid . ') has been killed'); } else { $logger->debug('Process #' . $pid . ' has been killed'); } unlink($pidPath); } else { if ($throwException) { throw new \RuntimeException('Cannot kill the process #' . $pid . ', please kill this process manually'); } $logger->critical('Cannot kill the process #' . $pid . ', please kill this process manually'); } }
function sig_handler($signo) { $log = getLog('queue/queued'); $log->setData("\r\n" . 'Signal Receive:' . $signo . ' ' . date('Y-m-d H:i:s')); $pids = @file(ROOT . 'logs/queue/pids'); if (is_array($pids)) { foreach ($pids as $pid) { list(, , $pid) = explode('_', $pid); if (!empty($pid)) { $pid = intval($pid); @posix_kill($pid, SIGTERM); if (file_exists(ROOT . 'logs/queue/pid/' . $pid)) { @unlink(ROOT . 'logs/queue/pid/' . $pid); } } } } switch ($signo) { case SIGHUP: @popen(ROOT . 'daemon/queue/queued.php 2>&1 > /dev/null &', "r"); break; } $log->setData("\r\n" . 'Signal Process Finished:' . date('Y-m-d H:i:s'))->write(); exit; }
public function stop() { if (!$this->process) { return; } $status = proc_get_status($this->process); if ($status['running']) { fclose($this->pipes[1]); //stdout fclose($this->pipes[2]); //stderr //get the parent pid of the process we want to kill $pPid = $status['pid']; //use ps to get all the children of this process, and kill them foreach (array_filter(preg_split('/\\s+/', `ps -o pid --no-heading --ppid {$pPid}`)) as $pid) { if (is_numeric($pid)) { posix_kill($pid, 9); // SIGKILL signal } } } fclose($this->pipes[0]); proc_terminate($this->process); $this->process = NULL; }
/** * Stop the jackrabbit server. If it is not running, silently return. */ public function stopServer() { $pid = $this->getServerPid(); if ($pid) { posix_kill($pid, SIGKILL); } }
protected function execute(InputInterface $input, OutputInterface $output) { $id = $input->getArgument('id'); // Do a cleanup $worker = new Resque\Worker('*'); $worker->cleanup(); if ($id) { if (false === ($worker = Resque\Worker::hostWorker($id))) { $this->log('There is no worker with id "' . $id . '".', Resque\Logger::ERROR); return; } $workers = array($worker); } else { $workers = Resque\Worker::hostWorkers(); } if (!count($workers)) { $this->log('<warn>There are no workers on this host</warn>'); } foreach ($workers as $worker) { $packet = $worker->getPacket(); $job_pid = (int) $packet['job_pid']; if ($job_pid and posix_kill($job_pid, 0)) { if (posix_kill($job_pid, SIGUSR1)) { $this->log('Worker <pop>' . $worker . '</pop> running job SIGUSR1 signal sent.'); } else { $this->log('Worker <pop>' . $worker . '</pop> <error>running job SIGUSR1 signal could not be sent.</error>'); } } else { $this->log('Worker <pop>' . $worker . '</pop> has no running job.'); } } }
/** * @param $strTestFile - the file to check for test-cases * @param $arrDefinedFunctions - all user-definied functions until now * @param $intParentPID - the process-pid of the parent * * @throw \Exception - if first parameter is not a string * @throw \Exception - if given file is not a file nor readable * @throw \Exception - if given parent-id is not an integer * * create a closure for execution in a fork. it will: * - include the given test-file * - find test-cases definied in test-file * - send list of test-cases to queue * - send SIGTERM to parent id and exit * **/ function getTestCaseClosure($strTestFile, array $arrDefinedFunctions, $intParentPID) { if (!is_string($strTestFile)) { throw new \Exception("first given parameter is not a string"); } if (!is_file($strTestFile) || !is_readable($strTestFile)) { throw new \Exception("given file is not a file or not readable: {$strTestFile}"); } if (!is_int($intParentPID)) { throw new \Exception("third given parameter is not an integer"); } return function () use($strTestFile, $arrDefinedFunctions, $intParentPID) { include $strTestFile; # get test-cases $arrAllFunctions = get_defined_functions(); $arrUserFunctions = $arrAllFunctions['user']; $arrDefinedFunctions = array_diff($arrUserFunctions, $arrDefinedFunctions); $arrTestCases = array(); foreach ($arrDefinedFunctions as $strFunction) { if (fnmatch('aphpunit\\testcases\\test*', $strFunction, FNM_NOESCAPE)) { $arrTestCases[] = $strFunction; } } # collect all information in this structure $arrMsgContent = array('file' => $strTestFile, 'functions' => $arrTestCases); # send the result to the queue $objQueue = new \SimpleIPC(QUEUE_IDENTIFIER); $objQueue->send(serialize($arrMsgContent)); # kill thread after sending parent a SIGTERM posix_kill($intParentPID, SIGTERM); exit; }; }
public function testRunningDaemonWithResistingWorker() { $writer = $this->getFileWriter(); $fork = $this->outerManager->fork(function () use($writer) { $handler = new NullHandler(); $builder = new Builder(array('worker1' => function () use($writer) { $writer("worker1.call"); }, 'worker2' => array('startup' => function () use($writer) { pcntl_signal(SIGQUIT, SIG_IGN); pcntl_signal(SIGINT, SIG_IGN); $writer("worker2.startup"); }, 'loop' => function () use($writer) { $writer("worker2.call"); }, 'interval' => 1))); $builder->setLogger(new Logger('test', array($handler)))->setShutdownTimeout(3); $daemon = $builder->build(); $daemon->setProcessName('testing'); $daemon->run(); }); sleep(1); $start = time(); $fork->kill(SIGQUIT); while (posix_kill($fork->getPid(), 0)) { pcntl_waitpid($fork->getPid(), $status, WNOHANG | WUNTRACED); usleep(100000); } $end = time(); $diff = $end - $start; $this->assertTrue($diff >= 2 && $diff <= 4, 'Has been killed in shutdown interval'); $content = file_get_contents($this->tempFile); $this->assertSame(1, preg_match_all('/worker1\\.call/', $content)); $this->assertSame(1, preg_match_all('/worker2\\.startup/', $content)); $calls = preg_match_all('/worker2\\.call/', $content); $this->assertTrue($calls >= 3 && $calls <= 5, 'Expected amount of worker2 calls'); }
public function killAll() { /** @var \Aurora\Worker $worker */ foreach ($this->workers as $worker) { posix_kill($worker->getPid(), SIGKILL); } }
protected function execute(InputInterface $input, OutputInterface $output) { $id = $input->getArgument('id'); // Do a cleanup $worker = new Resque\Worker('*'); $worker->cleanup(); if ($id) { if (false === ($worker = Resque\Worker::hostWorker($id))) { $this->log('There is no worker with id "' . $id . '".', Resque\Logger::ERROR); return; } $workers = array($worker); } else { $workers = Resque\Worker::hostWorkers(); } if (!count($workers)) { $this->log('<warn>There are no workers on this host</warn>'); } $sig = $input->getOption('force') ? 'TERM' : 'QUIT'; foreach ($workers as $worker) { if (posix_kill($worker->getPid(), constant('SIG' . $sig))) { $this->log('Worker <pop>' . $worker . '</pop> ' . $sig . ' signal sent.'); } else { $this->log('Worker <pop>' . $worker . '</pop> <error>could not send ' . $sig . ' signal.</error>'); } } }
/** * Sends the kill signal to all processes and removes them from the list. * * @return void */ public function killAllProcesses() { foreach ($this->processDetails as $pid => $processDetails) { $this->remove($processDetails); posix_kill($pid, SIGKILL); } }
protected function handleStop() { $pidFile = APPLICATION_PATH . '/runtime/jobserver.pid'; if (file_exists($pidFile)) { $pids = explode("|", file_get_contents($pidFile)); $del = 1; foreach ($pids as $pid) { $rs = posix_kill($pid, 15); if (!$rs) { $del = 0; echo "del_fail\r\n"; print_r(posix_get_last_error()); echo "\r\n"; } } if ($del) { echo "del_ok\r\n"; print_r(posix_get_last_error()); echo "\r\n"; do { unlink($pidFile); usleep(100000); } while (file_exists($pidFile)); return 0; } } return 1; }
/** * Start the task manager * * @param AbstractTask $task Task to start * * @return void */ public function start(AbstractTask $task) { $pid = pcntl_fork(); if ($pid == -1) { throw new \Exception('[Pid:' . getmypid() . '] Could not fork process'); } elseif ($pid) { $this->_activeThreads[$pid] = true; // Reached maximum number of threads allowed if ($this->maxThreads == count($this->_activeThreads)) { // Parent Process : Checking all children have ended (to avoid zombie / defunct threads) while (!empty($this->_activeThreads)) { $endedPid = pcntl_wait($status); if (-1 == $endedPid) { $this->_activeThreads = array(); } unset($this->_activeThreads[$endedPid]); } } } else { $task->initialize(); // On success if ($task->process()) { $task->onSuccess(); } else { $task->onFailure(); } posix_kill(getmypid(), 9); } pcntl_wait($status, WNOHANG); }
public function run() { $count = 0; $socket = stream_socket_server($this->socketString, &$errno, &$errstr); if (!$socket) { throw new RuntimeException($errstr); } while (true) { while (count($this->children) < $this->maxConnections) { $count++; $pid = pcntl_fork(); if ($pid == -1) { throw new RuntimeException('Couldn\'t fork'); } elseif ($pid == 0) { $this->createChild($socket, $count); exit; } $this->children[] = $pid; } while (pcntl_wait($status, WNOHANG or WUNTRACED) > 0) { usleep(500000); } while (list($key, $val) = each($this->children)) { if (!posix_kill($val, 0)) { unset($this->children[$key]); } } $this->children = array_values($this->children); usleep(500000); } }
/** * Terminate current process * * @param int $timeout * @param int $signal */ protected function _terminate($timeout = 10, $signal = 15) { foreach ($this->_getPidRecursive($this->getPid()) as $pid) { posix_kill($pid, $signal); } parent::stop($timeout, $signal); }
protected function execute(InputInterface $input, OutputInterface $output) { if ($input->getOption('all')) { $workers = \Resque_Worker::all(); } else { $worker = \Resque_Worker::find($input->getArgument('id')); if (!$worker) { $availableWorkers = \Resque_Worker::all(); if (!empty($availableWorkers)) { throw new \RuntimeException('A running worker must be specified'); } } $workers = $worker ? array($worker) : array(); } if (count($workers) <= 0) { $output->writeln(array('No workers running', '')); return; } $signal = $input->getOption('force') ? SIGTERM : SIGQUIT; foreach ($workers as $worker) { $output->writeln(sprintf('%s %s...', $signal === SIGTERM ? 'Force stopping' : 'Stopping', $worker)); list(, $pid) = explode(':', (string) $worker); posix_kill($pid, $signal); } $output->writeln(''); }
public static function checkContinue($cmd, $pidFile) { global $argv; switch ($cmd) { case 'start': case 'daemon': if (self::ifServerRunning($pidFile)) { die("{$argv[0]} is running\n"); } break; case 'stop': if (!self::ifServerRunning($pidFile)) { die("{$argv[0]} is not running\n"); } posix_kill((int) file_get_contents($pidFile), SIGTERM); die; break; default: echo "usage:\n"; echo " php {$argv[0]}\n"; echo " php {$argv[0]} daemon\n"; echo " php {$argv[0]} stop\n"; die; } }
/** * @test */ public function can_set_annotated_signal_handler() { $properties = array('ding' => array('log4php.properties' => RESOURCES_DIR . DIRECTORY_SEPARATOR . 'log4php.properties', 'factory' => array('bdef' => array('annotation' => array('scanDir' => array(__DIR__)))))); $container = ContainerImpl::getInstance($properties); posix_kill(posix_getpid(), SIGUSR1); $this->assertTrue(MySignalHandler2::$something); }
public static function tearDownAfterClass() { $s = proc_get_status(self::$phpserver); posix_kill($s['pid'], SIGKILL); proc_close(self::$phpserver); self::$phpserver = null; }
public static function tearDownAfterClass() { if (preg_match('/^WIN/', strtoupper(PHP_OS))) { echo "Please kill all Redis instances manually:" . PHP_EOL; } else { chdir(__DIR__); $directoryIterator = new DirectoryIterator(__DIR__); foreach ($directoryIterator as $item) { if (!$item->isfile() || !preg_match('/^redis\\-(.+)\\.pid$/', $item->getFilename())) { continue; } $pid = trim(file_get_contents($item->getFilename())); if (function_exists('posix_kill')) { posix_kill($pid, 15); } else { exec('kill ' . $pid); } } unlink('dump.rdb'); unlink('redis-master.conf'); unlink('redis-slave.conf'); unlink('redis-sentinel.conf'); rename('redis-master.conf.bak', 'redis-master.conf'); rename('redis-slave.conf.bak', 'redis-slave.conf'); rename('redis-sentinel.conf.bak', 'redis-sentinel.conf'); } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $consumer = $input->getArgument('consumer'); $producerName = sprintf('old_sound_rabbit_mq.%s_producer', $consumer); if (!$this->getContainer()->has($producerName)) { return $output->writeln(sprintf('<error>Consumer %s not found or its producer</error>', $consumer)); } $pids = $this->getConsumerPids($consumer); if (count($pids) === 0) { return $output->writeln('<comment>No consumer process found</comment>'); } foreach ($pids as $pid) { if (posix_kill($pid, SIGKILL)) { $output->writeln(sprintf('Signal SIGKILL sent to PID %d', $pid)); } else { $output->writeln(sprintf('<comment>Was unable to send SIGKILL to %d', $pid)); } } /** @var Producer $producer */ $producer = $this->getContainer()->get($producerName); for ($i = 0; $i < count($pids); $i++) { $producer->publish(serialize(array('_ping' => true))); } // Sleep 1 second and check for processes sleep(1); $stillAliveConsumers = $this->getConsumerPids($consumer); if (count($stillAliveConsumers) !== 0) { return $output->writeln(sprintf('<error>%d consumer processes seems to be found</error>', count($stillAliveConsumers))); } $output->writeln(sprintf('<info>%d consumer were terminated</info>', count($pids))); }
function killRedis($pid) { if (getmypid() !== $pid) { return; // don't kill from a forked worker } $config = file_get_contents(REDIS_CONF); if (!preg_match('#^\\s*pidfile\\s+([^\\s]+)#m', $config, $matches)) { return; } $pidFile = TEST_MISC . '/' . $matches[1]; if (file_exists($pidFile)) { $pid = trim(file_get_contents($pidFile)); posix_kill((int) $pid, 9); if (is_file($pidFile)) { unlink($pidFile); } } // Remove the redis database if (!preg_match('#^\\s*dir\\s+([^\\s]+)#m', $config, $matches)) { return; } $dir = $matches[1]; if (!preg_match('#^\\s*dbfilename\\s+([^\\s]+)#m', $config, $matches)) { return; } $filename = TEST_MISC . '/' . $dir . '/' . $matches[1]; if (is_file($filename)) { unlink($filename); } }
/** * Pause job. * @param string $sid sid. * @return bool */ public function pauseJob($sid) { if (!@is_file("{$this->tmpDir}/{$sid}.stat")) { return false; } return $this->getStats('is_running', $sid) && posix_kill($this->getStats('pid', $sid), 15); }
function _exclusiveLock($fname = false) { $mutex =& $this->_mutex(); while (true) { $timestamp = $mutex->lockTS(); // Note: This does not lock, only checks what the timestamp is. if ($timestamp === false) { if (!$mutex->lock()) { eZDebug::writeWarning("Failed to acquire lock for file " . $this->filePath); return false; } $mutex->setMeta('pid', getmypid()); return true; } if ($timestamp >= time() - $this->lifetime) { usleep(500000); // Sleep 0.5 second continue; } $oldPid = $mutex->meta('pid'); if (is_numeric($oldPid) && $oldPid != 0 && function_exists('posix_kill')) { posix_kill($oldPid, 9); } if (!$mutex->steal()) { eZDebug::writeWarning("Failed to steal lock for file " . $this->filePath . " from PID {$oldPid}"); return false; } $mutex->setMeta('pid', getmypid()); return true; } }
/** * close stream * @return mixed */ public function close() { if (!is_resource($this->process)) { return; } $status = proc_get_status($this->process); if ($status['running'] == true) { //process ran too long, kill it //close all pipes that are still open @fclose($this->pipes[0]); //stdin @fclose($this->pipes[1]); //stdout @fclose($this->pipes[2]); //stderr //get the parent pid of the process we want to kill $parent_pid = $status['pid']; //use ps to get all the children of this process, and kill them $pids = preg_split('/\\s+/', `ps -o pid --no-heading --ppid {$parent_pid}`); foreach ($pids as $pid) { if (is_numeric($pid)) { posix_kill($pid, 9); //9 is the SIGKILL signal } } proc_close($this->process); } }