function task_shutdown() { $pid = posix_getpid(); if (file_exists(LOCK_DIRECTORY . "/update_daemon-{$pid}.lock")) { unlink(LOCK_DIRECTORY . "/update_daemon-{$pid}.lock"); } }
public static function start() { self::daemonize(); self::$pid = posix_getpid(); file_put_contents('app.pid', self::$pid); self::monitorWorks(); }
public static function _init_mysql($config = array()) { if (empty($config)) { // 记住不要把原来有的配置信息给强制换成$GLOBALS['config']['db'],否则换数据库会有问题 self::$config = empty(self::$config) ? $GLOBALS['config']['db'] : self::$config; } else { self::$config = $config; } if (!self::$conn) { self::$conn = @mysqli_connect(self::$config['host'], self::$config['user'], self::$config['pass'], self::$config['name'], self::$config['port']); if (mysqli_connect_errno()) { self::$conn_fail++; $errmsg = 'Mysql Connect failed[' . self::$conn_fail . ']: ' . mysqli_connect_error(); echo util::colorize(date("H:i:s") . " {$errmsg}\n\n", 'fail'); log::add($errmsg, "Error"); // 连接失败5次,中断进程 if (self::$conn_fail >= 5) { exit(250); } self::_init_mysql($config); } else { // 连接成功清零 self::$conn_fail = 0; self::$worker_pid = function_exists('posix_getpid') ? posix_getpid() : 0; mysqli_query(self::$conn, " SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary, sql_mode='' "); } } else { $curr_pid = function_exists('posix_getpid') ? posix_getpid() : 0; // 如果父进程已经生成资源就释放重新生成,因为多进程不能共享连接资源 if (self::$worker_pid != $curr_pid) { self::reset_connect(); } } }
function send() { $pid = posix_getpid(); $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞 $client->on("connect", function (swoole_client $cli) use($pid) { $data = microtime(true); lg("[{$pid}] Send: {$data}", __LINE__); $cli->send($data); }); $client->on("receive", function (swoole_client $cli, $data) use($pid) { lg("[{$pid}] Received: {$data}", __LINE__); $cli->close(); }); $client->on("error", function (swoole_client $cli) use($pid) { $cli->close(); //lg("[$pid] error then conn close", __LINE__); exit(0); }); $client->on("close", function (swoole_client $cli) use($pid) { //lg("[$pid] conn close", __LINE__); }); $client->connect('127.0.0.1', 8001, 0.5); //lg("[$pid] create conn succ", __LINE__); exit(0); }
function git_diff($proj, $from, $from_name, $to, $to_name) { global $gitphp_conf; $from_tmp = "/dev/null"; $to_tmp = "/dev/null"; if (function_exists('posix_getpid')) { $pid = posix_getpid(); } else { $pid = rand(); } if (isset($from)) { $from_tmp = $gitphp_conf['gittmp'] . "gitphp_" . $pid . "_from"; git_cat_file($proj, $from, $from_tmp); } if (isset($to)) { $to_tmp = $gitphp_conf['gittmp'] . "gitphp_" . $pid . "_to"; git_cat_file($proj, $to, $to_tmp); } $out = shell_exec($gitphp_conf['diffbin'] . " -u -p -L '" . $from_name . "' -L '" . $to_name . "' " . $from_tmp . " " . $to_tmp); if (isset($from)) { unlink($from_tmp); } if (isset($to)) { unlink($to_tmp); } return $out; }
public static function prn_log($level, $msg) { $log_level_str = array('TRACE', 'DEBUG', 'INFO', 'NOTICE', 'WARNING', 'ERROR'); if ($level >= self::$log_level) { echo '[' . posix_getpid() . '.' . date("Y-m-d H:i:s") . ']' . sprintf('%-9s ', "[{$log_level_str[$level]}]") . $msg . "\n"; } }
private function createJob() { $tokenData = self::$sapiClient->verifyToken(); /** @var ObjectEncryptor $configEncryptor */ $configEncryptor = self::$kernel->getContainer()->get('syrup.object_encryptor'); return new Job($configEncryptor, ['id' => self::$sapiClient->generateId(), 'runId' => self::$sapiClient->generateId(), 'project' => ['id' => $tokenData['owner']['id'], 'name' => $tokenData['owner']['name']], 'token' => ['id' => $tokenData['id'], 'description' => $tokenData['description'], 'token' => self::$encryptor->encrypt(self::$sapiClient->getTokenString())], 'component' => SYRUP_APP_NAME, 'command' => 'run', 'process' => ['host' => 'test', 'pid' => posix_getpid()], 'createdTime' => date('c')], null, null, null); }
public static function init() { self::$pid = \posix_getpid(); self::$ppid = \posix_getppid(); self::$child = array(); self::$alias = array(); self::$user_events = array(); self::$shm_to_pid = array(); self::$status['start_time'] = time(); // self::$shm_to_parent = -1; if (!self::$do_once) { // 初始化事件对象 if (extension_loaded('libevent')) { self::$events = new Libevent(); } else { self::$events = new Select(); } self::$shm = new Shm(__FILE__, 'a'); // 注册用户信号SIGUSR1处理函数 self::onSysEvent(SIGUSR1, EventInterface::EV_SIGNAL, array("\\cli\\proc\\Process", 'defaultSigusr1Cbk')); // 注册子进程退出处理函数 self::onSysEvent(SIGCHLD, EventInterface::EV_SIGNAL, array("\\cli\\proc\\Process", 'defaultSigchldCbk')); // 注册用户信号SIGUSR2处理函数 self::onSysEvent(SIGUSR2, EventInterface::EV_SIGNAL, array("\\cli\\proc\\Process", 'defaultSigusr2Cbk')); // 注册exit回调函数 register_shutdown_function(function () { Process::closeShm(); }); self::$do_once = true; } }
public function createPid() { $pid = posix_getpid(); file_put_contents($this->getPidFilename(), $pid); register_shutdown_function([$this, 'removePid']); return $pid; }
function wdiff_compute($text1, $text2) { global $ErrorCreatingTemp, $ErrorWritingTemp, $TempDir, $WdiffCmd; global $WdiffLibrary; $num = posix_getpid(); // Comment if running on Windows. // $num = rand(); // Uncomment if running on Windows. $temp1 = $TempDir . '/wiki_' . $num . '_1.txt'; $temp2 = $TempDir . '/wiki_' . $num . '_2.txt'; if (!($h1 = fopen($temp1, 'w')) || !($h2 = fopen($temp2, 'w'))) { die($ErrorCreatingTemp); } $fw1 = fwrite($h1, $text1); $fw2 = fwrite($h2, $text2); if ($fw1 === false || strlen($text1) > 0 && $fw1 == 0 || $fw2 === false || strlen($text2) > 0 && $fw2 == 0) { die($ErrorWritingTemp); } fclose($h1); fclose($h2); if ($WdiffLibrary) { putenv('LD_LIBRARY_PATH=/disk'); } exec($WdiffCmd . ' -n --start-delete="<DEL>" --end-delete="</DEL>" --start-insert="<INS>" --end-insert="</INS>" ' . $temp1 . ' ' . $temp2, $output); unlink($temp1); unlink($temp2); $output = implode("\n", $output); return $output; }
/** * мастерский рабочий цикл */ public function run() { try { static::log('starting master (PID ' . posix_getpid() . ')....'); //задаем приоритет процесса в ОС proc_nice($this->priority); //включаем сборщик циклических зависимостей gc_enable(); //выполняем функцию приложения до рабочего цикла call_user_func([$this->appl, 'baseOnRun']); //самый главный цикл while (TRUE) { if (TRUE === call_user_func([$this->appl, 'baseRun'])) { //прекращаем цикл break; } //ожидаем заданное время для получения сигнала операционной системы $this->sigwait(); //если сигнал был получен, вызываем связанную с ним функцию pcntl_signal_dispatch(); } } catch (\Exception $e) { $this->shutdown(); } }
public static function init($pcacher = null, $expire = 0) { return function ($info, $buffered = false) use($pcacher, $expire) { if (!$pcacher) { $pcacher = \Leb_Dao_Memcache::getInstance('applog'); } if (!$pcacher) { throw new \LogicException('Invalid cacher object.'); } // 8 = 4 + 2 + 2 // t + p + c // 64 = 32 + 10 + 15 + 7 // t + mt + p + c $bptime = explode(' ', microtime(false)); $pid = function_exists('posix_getpid') ? posix_getpid() : getmypid(); // $uid = (time() << 16 | ($pid % 0xFFFF)) << 16 | ((++ \Leb_Analog::$counter) % 0xFFFF); $uid = $bptime[1] << 10 | intval($bptime[0] * 1000); $uid = $uid << 15 | $pid % 0xfffe; $uid = $uid << 7 | ++\Leb_Analog::$counter % 0xfe; // $uuid = sprintf('%u', $uid); // var_dump($bptime[1], intval($bptime[0] * 1000), $pid, \Leb_Analog::$counter, $uid, $uuid); // exit; $bret = true; $bret = $pcacher->set($uid, json_encode($info), array('expire' => $expire)); if ($bret) { return $uid; } return $bret; }; }
public function randStop($sleep_time) { if ($sleep_time > 1500000) { echo "process stopped : " . posix_getpid() . "\n"; $this->stop(); } }
/** * Handles an AWS client event * * @param EventInterface $event An Event object * @param int $attempt optional Attempt number */ private function handleEvent(EventInterface $event, $attempt = 0) { try { $environment = $this->aws->getEnvironment(); if ($environment instanceof \Scalr_Environment) { $eventId = self::EVENT_ID_REQUEST_SENT; if ($event instanceof ErrorResponseEvent) { $errorData = $event->exception->getErrorData(); if ($errorData instanceof ErrorData && $errorData->getCode() == ErrorData::ERR_REQUEST_LIMIT_EXCEEDED) { $eventId = self::EVENT_ID_ERROR_REQUEST_LIMIT_EXCEEDED; } else { return; } } $db = $this->getDb(); $pid = function_exists('posix_getpid') ? posix_getpid() : null; $apicall = isset($event->apicall) ? $event->apicall : null; $db->Execute("\n INSERT INTO `" . self::DB_TABLE_NAME . "`\n SET envid = ?,\n event = ?,\n pid = ?,\n apicall = ?\n ", array($environment->id, $eventId, $pid, $apicall)); } } catch (\Exception $e) { if ($attempt == 0 && !$db->GetOne("SHOW TABLES LIKE ?", array(self::DB_TABLE_NAME))) { $this->createStorage(); return $this->handleEvent($event, 1); } //It should not cause process termination trigger_error($e->getMessage(), E_USER_WARNING); } }
/** * 进程启动 */ public function start() { // 安装信号处理函数 $this->installSignal(); // 添加accept事件 $ret = $this->event->add($this->mainSocket, Man\Core\Events\BaseEvent::EV_READ, array($this, 'accept')); // 创建内部通信套接字 $start_port = Man\Core\Lib\Config::get($this->workerName . '.lan_port_start'); $this->lanPort = $start_port - posix_getppid() + posix_getpid(); $this->lanIp = Man\Core\Lib\Config::get($this->workerName . '.lan_ip'); if (!$this->lanIp) { $this->notice($this->workerName . '.lan_ip not set'); $this->lanIp = '127.0.0.1'; } $error_no = 0; $error_msg = ''; $this->innerMainSocket = stream_socket_server("udp://" . $this->lanIp . ':' . $this->lanPort, $error_no, $error_msg, STREAM_SERVER_BIND); if (!$this->innerMainSocket) { $this->notice('create innerMainSocket fail and exit ' . $error_no . ':' . $error_msg); sleep(1); exit(0); } else { stream_set_blocking($this->innerMainSocket, 0); } $this->registerAddress("udp://" . $this->lanIp . ':' . $this->lanPort); // 添加读udp事件 $this->event->add($this->innerMainSocket, Man\Core\Events\BaseEvent::EV_READ, array($this, 'recvUdp')); // 初始化到worker的通信地址 $this->initWorkerAddresses(); // 主体循环,整个子进程会阻塞在这个函数上 $ret = $this->event->loop(); $this->notice('worker loop exit'); exit(0); }
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 bool $getOnlyKey * @return mixed|string */ public function draw($getOnlyKey = false) { mt_srand(crc32(time() ^ posix_getpid() + mt_rand())); $rand = mt_rand(0, $this->instance->total() - 1); $key = $this->instance->getList()[$rand]; return $getOnlyKey === true ? $key : $this->instance->get($key); }
/** * Constructor. * * @param Master $master The master object * @param integer $pid The child process id or null if this is the child * * @throws \Exception * @throws \RuntimeException */ public function __construct(Master $master, $pid = null) { $this->master = $master; $directions = array('up', 'down'); if (null === $pid) { // child $pid = posix_getpid(); $pPid = posix_getppid(); $modes = array('write', 'read'); } else { // parent $pPid = null; $modes = array('read', 'write'); } $this->pid = $pid; $this->ppid = $pPid; foreach (array_combine($directions, $modes) as $direction => $mode) { $fifo = $this->getPath($direction); if (!file_exists($fifo) && !posix_mkfifo($fifo, 0600) && 17 !== ($error = posix_get_last_error())) { throw new \Exception(sprintf('Error while creating FIFO: %s (%d)', posix_strerror($error), $error)); } $this->{$mode} = fopen($fifo, $mode[0]); if (false === ($this->{$mode} = fopen($fifo, $mode[0]))) { throw new \RuntimeException(sprintf('Unable to open %s FIFO.', $mode)); } } }
/** * @throws \Net\Bazzline\Component\ProcessForkManager\RuntimeException */ public function execute() { $identifier = 'task (' . posix_getpid() . ' / ' . $this->getParentProcessId() . ')'; $workingDataSet = array(); echo $identifier . ' says hello' . PHP_EOL; for ($iterator = 0; $iterator < $this->numberOfDataMultiplication; ++$iterator) { //begin creating one megabyte of data //taken from https://github.com/stevleibelt/examples/blob/master/php/array/createOneMegaByteOfData.php $anotherRound = true; $data = array(); $initialMemoryUsage = memory_get_usage(true); $anotherIterator = 0; $memoryUsageInMegaByteToGenerate = 1; while ($anotherRound) { $data[] = $anotherIterator; $currentMemoryUsage = memory_get_usage(true) - $initialMemoryUsage; $currentMemoryUsageInMegaBytes = $currentMemoryUsage / (1024 * 1024); if ($currentMemoryUsageInMegaBytes === $memoryUsageInMegaByteToGenerate) { $anotherRound = false; } ++$anotherIterator; } //end creating one megabyte of data $workingDataSet[] = $data; sleep(1); } echo $identifier . ' says goodbye' . PHP_EOL; }
public function run() { $job = $this->job; // Try to fork process. $childPid = pcntl_fork(); // Force reconnect to redis for parent and child due to bug in PhpRedis // (https://github.com/nicolasff/phpredis/issues/474). \Yii::app()->redis->getClient(true); if ($childPid > 0) { return $childPid; } elseif ($childPid < 0) { // If we're failed to fork process, restore job and exit. \Yii::app()->yiiq->restore($job->id); return; } // We are child - get our pid. $childPid = posix_getpid(); $metadata = $job->metadata; $status = $job->status; $this->owner->setProcessTitle('job', $metadata->queue, 'executing ' . $metadata->id . ' (' . $metadata->class . ')'); \Yii::trace('Starting job ' . $metadata->queue . ':' . $job->id . ' (' . $metadata->class . ')...'); $status->markAsStarted($childPid); $payload = $job->payload; $result = $payload->execute($metadata->args); if ($metadata->type === Yiiq::TYPE_REPEATABLE) { $status->markAsStopped(); } else { $metadata->delete(); $job->result->save($result); $status->markAsCompleted(); } \Yii::trace('Job ' . $metadata->queue . ':' . $job->id . ' done.'); exit(0); }
function ctx_log_msg($func, $text, $type) { global $_context_log; if ($_context_log) { fprintf($_context_log, "%f %s %d %d %s %s %s\n", microtime(true), php_uname('n'), posix_getpid(), posix_getpid(), $type, $func, $text); } }
protected function start() { if ($this->pidManager->get()) { echo "ERROR: plumber is already running.\n"; return; } echo "plumber started.\n"; if ($this->config['daemonize']) { swoole_process::daemon(); } $this->logger = new Logger(['log_path' => $this->config['log_path']]); $this->output = new Logger(['log_path' => $this->config['output_path']]); $this->logger->info('plumber starting...'); $this->stats = $stats = $this->createListenerStats(); swoole_set_process_name('plumber: master'); $this->workers = $this->createWorkers($stats); $this->registerSignal(); $this->pidManager->save(posix_getpid()); swoole_timer_tick(1000, function ($timerId) { $statses = $this->stats->getAll(); foreach ($statses as $pid => $s) { if ($s['last_update'] + $this->config['reserve_timeout'] + $this->config['execute_timeout'] > time()) { continue; } if (!$s['timeout']) { $this->logger->notice("process #{$pid} last upadte at " . date('Y-m-d H:i:s') . ', it is timeout.', $s); $this->stats->timeout($pid); } } }); }
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; } } }
public function fork($workerClosure, $numOfWorkers) { if (is_callable($workerClosure)) { for ($i = 1; $i <= $numOfWorkers; $i++) { $childProcess = System::load("child_process")->fork(); $pid = $childProcess->getPid(); if ($pid == -1) { $childProcess->emit("error", $pid); exit; } else { if ($pid > 0) { //Successfully forked a worker process $process = new ChildProcess($pid); $this->workers[$pid] = new Worker($process); } else { if ($pid == 0) { //we are now in the worker process $pid = posix_getpid(); $process = new ChildProcess($pid); $worker = new Worker($process); $this->workers[$pid] = $worker; //immediately record workers in the queue call_user_func_array($workerClosure, array($worker)); } } } } } }
/** * @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); }
function diff_compute($text1, $text2) { global $TempDir, $DiffCmd; $num = function_exists('posix_getpid') ? posix_getpid() : rand(); $temp1 = $TempDir . '/wiki_' . $num . '_1.txt'; $temp2 = $TempDir . '/wiki_' . $num . '_2.txt'; if (!($h1 = fopen($temp1, 'w')) || !($h2 = fopen($temp2, 'w'))) { die(LIB_ErrorCreatingTemp); } if (fwrite($h1, $text1) < 0 || fwrite($h2, $text2) < 0) { die(LIB_ErrorWritingTemp); } fclose($h1); fclose($h2); if (ini_get('safe_mode') and ini_get('safe_mode_exec_dir') != dirname($DiffCmd)) { $diff = LIB_NoDiffAvailableSafeMode; } else { if (!file_exists($DiffCmd) or !is_readable($DiffCmd)) { $diff = LIB_NoDiffAvailable; } else { $output = array(); exec("{$DiffCmd} {$temp1} {$temp2}", $output); $diff = join("\n", $output); } } unlink($temp1); unlink($temp2); return $diff; }
public function __construct($server, $master) { $this->_server = $server; $this->_services = array($this->getIdByConnection($master) => $master); $this->master = $master; $this->pid = posix_getpid(); }
public function __construct($server, $service, $master) { $this->_server = $server; $this->_service = $service; $this->_master = $master; $this->pid = posix_getpid(); }
function __get_swoole_app(array $config) { $app = new \Owl\Swoole\Application($config['server']['ip'], $config['server']['port']); if (isset($config['swoole_setting']) && $config['swoole_setting']) { $app->getSwooleServer()->set($config['swoole_setting']); } $server = $app->getSwooleServer(); $server->on('start', function () use($config) { $pid = posix_getpid(); if (isset($config['server']['pid_file'])) { file_put_contents($config['server']['pid_file'], $pid); } echo sprintf("Server PID: %d\n", $pid); echo sprintf("Listening http://%s:%d/ ...\n", $config['server']['ip'], $config['server']['port']); }); $server->on('shutdown', function () use($config) { if (isset($config['server']['pid_file']) && file_exists($config['server']['pid_file'])) { unlink($config['server']['pid_file']); } }); // 在workstart之后再bootstrap,就可以通过server reload重置应用配置 $server->on('workerstart', function () { __bootstrap(); }); return __ini_app($app); }
function worker() { $lost = 0; if (!file_exists($this->shm_key)) { file_put_contents($this->shm_key, microtime(true)); } if ($this->show_detail) { $start = microtime(true); } $this->pid = posix_getpid(); for ($i = 0; $i < $this->process_req_num; $i++) { $func = $this->test_func; if (!$func($this)) { $lost++; } } if ($this->show_detail) { $log = $this->pid . "#\ttotal_use(s):" . substr(microtime(true) - $start, 0, 5); $log .= "\tconnect(ms):" . substr($this->max_conn_time * 1000, 0, 5); $log .= "\twrite(ms):" . substr($this->max_write_time * 1000, 0, 5); $log .= "\tread(ms):" . substr($this->max_read_time * 1000, 0, 5); file_put_contents($this->tmp_dir . 'lost_' . $this->pid . '.log', $lost . "\n" . $log); } else { file_put_contents($this->tmp_dir . 'lost_' . $this->pid . '.log', $lost); } exit(0); }