• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP posix_getpid函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中posix_getpid函数的典型用法代码示例。如果您正苦于以下问题:PHP posix_getpid函数的具体用法?PHP posix_getpid怎么用?PHP posix_getpid使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了posix_getpid函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: task_shutdown

function task_shutdown()
{
    $pid = posix_getpid();
    if (file_exists(LOCK_DIRECTORY . "/update_daemon-{$pid}.lock")) {
        unlink(LOCK_DIRECTORY . "/update_daemon-{$pid}.lock");
    }
}
开发者ID:rolfkleef,项目名称:Tiny-Tiny-RSS,代码行数:7,代码来源:update_daemon2.php


示例2: start

 public static function start()
 {
     self::daemonize();
     self::$pid = posix_getpid();
     file_put_contents('app.pid', self::$pid);
     self::monitorWorks();
 }
开发者ID:sdlyhu,项目名称:Demo,代码行数:7,代码来源:server.php


示例3: _init_mysql

 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();
         }
     }
 }
开发者ID:jackyxie,项目名称:phpspider,代码行数:34,代码来源:db.php


示例4: send

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);
}
开发者ID:jinguanio,项目名称:david,代码行数:26,代码来源:multi_cli.php


示例5: git_diff

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;
}
开发者ID:nterray,项目名称:tuleap,代码行数:27,代码来源:gitutil.git_diff.php


示例6: prn_log

 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";
     }
 }
开发者ID:loder,项目名称:asf,代码行数:7,代码来源:log.php


示例7: createJob

 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);
 }
开发者ID:ErikZigo,项目名称:syrup,代码行数:7,代码来源:SearchTest.php


示例8: init

 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;
     }
 }
开发者ID:hduwzy,项目名称:test,代码行数:31,代码来源:Process.php


示例9: createPid

 public function createPid()
 {
     $pid = posix_getpid();
     file_put_contents($this->getPidFilename(), $pid);
     register_shutdown_function([$this, 'removePid']);
     return $pid;
 }
开发者ID:alexlvcom,项目名称:TaskRunner,代码行数:7,代码来源:PidTrait.php


示例10: wdiff_compute

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;
}
开发者ID:apenwarr,项目名称:gracefultavi,代码行数:28,代码来源:diff.php


示例11: run

 /**
  * мастерский рабочий цикл
  */
 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();
     }
 }
开发者ID:yutas,项目名称:phpdaemon,代码行数:28,代码来源:Master.php


示例12: init

 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;
     };
 }
开发者ID:spwx820,项目名称:lock-money-admin_cp,代码行数:30,代码来源:couchbase.php


示例13: randStop

 public function randStop($sleep_time)
 {
     if ($sleep_time > 1500000) {
         echo "process stopped : " . posix_getpid() . "\n";
         $this->stop();
     }
 }
开发者ID:LWFeng,项目名称:hush,代码行数:7,代码来源:Process.php


示例14: handleEvent

 /**
  * 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);
     }
 }
开发者ID:recipe,项目名称:scalr,代码行数:34,代码来源:StatisticsPlugin.php


示例15: start

 /**
  * 进程启动
  */
 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);
 }
开发者ID:bennysuh,项目名称:workerman-game,代码行数:37,代码来源:GameGateway.php


示例16: execute

 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;
     }
 }
开发者ID:hofmeister,项目名称:Pimple,代码行数:27,代码来源:Thread.php


示例17: draw

 /**
  * @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);
 }
开发者ID:destinylab,项目名称:lottery-poetry-engine,代码行数:11,代码来源:Engine.php


示例18: __construct

 /**
  * 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));
         }
     }
 }
开发者ID:gcds,项目名称:morker,代码行数:36,代码来源:Fifo.php


示例19: execute

 /**
  * @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;
 }
开发者ID:jamiefifty,项目名称:php_component_process_fork_manager,代码行数:31,代码来源:ExampleTask.php


示例20: run

 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);
 }
开发者ID:herroffizier,项目名称:yiiq,代码行数:34,代码来源:Runner.php



注:本文中的posix_getpid函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP posix_getppid函数代码示例发布时间:2022-05-15
下一篇:
PHP posix_getpgid函数代码示例发布时间:2022-05-15
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap