/** * @param ConsoleCommandEvent $event * * @return void * @throws CommandAlreadyRunningException */ public function onConsoleCommand(ConsoleCommandEvent $event) { // generate pid file name $commandName = $event->getCommand()->getName(); // check for exceptions if (in_array($commandName, $this->exceptionsList)) { return; } $clearedCommandName = $this->cleanString($commandName); $pidFile = $this->pidFile = $this->pidDirectory . "/{$clearedCommandName}.pid"; // check if command is already executing if (file_exists($pidFile)) { $pidOfRunningCommand = file_get_contents($pidFile); $elements = explode(":", $pidOfRunningCommand); if ($elements[0] == gethostname()) { if (posix_getpgid($elements[1]) !== false) { throw (new CommandAlreadyRunningException())->setCommandName($commandName)->setPidNumber($pidOfRunningCommand); } else { // pid file exist but the process is not running anymore unlink($pidFile); } } else { throw (new CommandAlreadyRunningException())->setCommandName($commandName)->setPidNumber($pidOfRunningCommand); } } // if is not already executing create pid file //file_put_contents($pidFile, getmypid()); // Añadimos hostname para verificar desde que frontal se estan ejecutando $string = gethostname() . ":" . getmypid(); file_put_contents($pidFile, $string); // register shutdown function to remove pid file in case of unexpected exit register_shutdown_function(array($this, 'shutDown'), null, $pidFile); }
private function checkPid($check) { if (posix_getpgid($check) !== false) { return true; } return false; }
/** * @param int $wait max time to wait to acquire lock (seconds) * @return bool TRUE if acquired; else false */ function acquire($wait) { $totalDelay = 0; // total total spent waiting so far (seconds) $nextDelay = 0; while ($totalDelay < $wait) { if ($nextDelay) { sleep($nextDelay); $totalDelay += $nextDelay; } if (!file_exists($this->lockFile)) { file_put_contents($this->lockFile, $this->pid); return TRUE; } $lockPid = (int) trim(file_get_contents($this->lockFile)); if ($lockPid == $this->pid) { return TRUE; } if (!posix_getpgid($lockPid)) { file_put_contents($this->lockFile, $this->pid); return TRUE; } $nextDelay = rand($this->minDelay, min($this->maxDelay, $wait - $totalDelay)); } return FALSE; }
function dmn_getpids($nodes, $isstatus = false) { if ($isstatus) { if (file_exists(DMN_CTLSTATUSAUTO_SEMAPHORE) && posix_getpgid(intval(file_get_contents(DMN_CTLSTATUSAUTO_SEMAPHORE))) !== false) { xecho("Already running (PID " . sprintf('%d', file_get_contents(DMN_CTLSTATUSAUTO_SEMAPHORE)) . ")\n"); die(10); } file_put_contents(DMN_CTLSTATUSAUTO_SEMAPHORE, sprintf('%s', getmypid())); } $dmnpid = array(); foreach ($nodes as $uname => $node) { if (is_dir(DMN_PID_PATH . $uname)) { $conf = new DashConfig($uname); if ($conf->isConfigLoaded()) { if ($node['NodeTestNet'] != $conf->getconfig('testnet')) { xecho("{$uname}: Configuration inconsistency (testnet/" . $node['NodeTestNet'] . "/" . $conf->getconfig('testnet') . ")\n"); } if ($node['NodeEnabled'] != $conf->getmnctlconfig('enable')) { xecho("{$uname}: Configuration inconsistency (enable/" . $node['NodeEnabled'] . "/" . $conf->getmnctlconfig('enable') . ")\n"); } $pid = dmn_getpid($uname, $conf->getconfig('testnet') == '1'); $dmnpiditem = array('pid' => $pid, 'uname' => $uname, 'conf' => $conf, 'type' => $node['NodeType'], 'enabled' => $node['NodeEnabled'] == 1, 'testnet' => $node['NodeTestNet'] == 1, 'dashd' => $node['VersionPath'], 'currentbin' => '', 'keeprunning' => $node['KeepRunning'] == 1, 'keepuptodate' => $node['KeepUpToDate'] == 1, 'versionraw' => $node['VersionRaw'], 'versiondisplay' => $node['VersionDisplay'], 'versionhandling' => $node['VersionHandling']); if ($pid !== false) { if (file_exists('/proc/' . $pid . '/exe')) { $currentbin = readlink('/proc/' . $pid . '/exe'); $dmnpiditem['currentbin'] = $currentbin; if ($currentbin != $node['VersionPath']) { xecho("{$uname}: Binary mismatch ({$currentbin} != " . $node['VersionPath'] . ")"); /* if ($dmnpiditem['keepuptodate']) { echo " [Restarting to fix]\n"; dmn_startstop(array($dmnpiditem),"restart",($node['NodeTestNet'] == 1),$node['NodeType']); sleep(3); $pid = dmn_getpid($uname,($conf->getconfig('testnet') == '1')); $dmnpiditem['pid'] = $pid; if (($pid !== false) && (file_exists('/proc/'.$pid.'/exe'))) { $currentbin = readlink('/proc/'.$pid.'/exe'); $dmnpiditem['currentbin'] = $currentbin; if ($currentbin != $node['VersionPath']) { xecho("$uname: Binary mismatch ($currentbin != ".$node['VersionPath'].") [Restart failed, need admin]\n"); } } } else { */ echo " [Restart to fix]\n"; // } } } else { xecho("{$uname}: process ID {$pid} has no binary information (crashed?)\n"); } } else { xecho("{$uname}: process ID not found\n"); } $dmnpid[] = $dmnpiditem; } } } usort($dmnpid, "dmnpidcmp"); return $dmnpid; }
/** * Create a ParallelChildCollector that will collect * issues as normal, but emit them to a message queue * for collection by a * \Phan\Output\Collector\ParallelParentCollector. */ public function __construct() { assert(extension_loaded('sysvsem'), 'PHP must be compiled with --enable-sysvsem in order to use -j(>=2).'); assert(extension_loaded('sysvmsg'), 'PHP must be compiled with --enable-sysvmsg in order to use -j(>=2).'); // Create a message queue for this process group $message_queue_key = posix_getpgid(posix_getpid()); $this->message_queue_resource = msg_get_queue($message_queue_key); }
public function testCheckIfPidIsRunning() { // Start up a testing webserver. $host = "localhost"; $port = 8080; $script = realpath(__DIR__ . "/routers/router-200.php"); $server = new ShamServer($host, $port, $script); $pid = $server->getPid(); $this->assertNotFalse(posix_getpgid($pid)); $server->stop(); }
/** * public static function running * * @access public * @return bool $running */ public static function is_running() { if (!file_exists(Config::$pid_file)) { return false; } $pid = file_get_contents(Config::$pid_file); if (posix_getpgid($pid) === false) { unlink(Config::$pid_file); return false; } return true; }
protected function getRelatedConsoleNodeProcess() { $consoleNodeProcess = $this->getConsoleNodeProcessRepository()->findOneBy(['name' => $this->getName(), 'consoleNode' => $this->consoleNode]); if ($consoleNodeProcess instanceof ConsoleNodeProcessInterface === false) { $this->writeLog(self::MSG_COMMAND_NOT_RUNNING, [$this->getName(), $this->consoleNode->getHostName()]); exit; } if (posix_getpgid($consoleNodeProcess->getPid()) === false) { $this->writeLog(self::MSG_COMMAND_MAY_HAVE_CRASHED, [$this->getName(), $this->consoleNode->getHostName()]); } return $consoleNodeProcess; }
/** * Create a ParallelParentCollector that will collect * issues via a message queue. You'll want to do the * real collection via * \Phan\Output\Collector\ParallelChildCollector. * * @param IssueCollectorInterface $base_collector * A collector must be given to which collected issues * will be passed */ public function __construct(IssueCollectorInterface $base_collector) { assert(extension_loaded('sysvsem'), 'PHP must be compiled with --enable-sysvsem in order to use -j(>=2).'); assert(extension_loaded('sysvmsg'), 'PHP must be compiled with --enable-sysvmsg in order to use -j(>=2).'); $this->base_collector = $base_collector; // Create a message queue for this process group $message_queue_key = posix_getpgid(posix_getpid()); $this->message_queue_resource = msg_get_queue($message_queue_key); // Listen for ALARMS that indicate we should flush // the queue pcntl_sigprocmask(SIG_UNBLOCK, array(SIGUSR1), $old); pcntl_signal(SIGUSR1, function () { $this->readQueuedIssues(); }); }
public function stop() { $pid = @file_get_contents($this->config['pid']); if ($pid) { posix_kill($pid, SIGTERM); for ($i = 0; $i = 10; $i++) { sleep(1); if (!posix_getpgid($pid)) { unlink($this->config['pid']); return; } } die("don't stopped\r\n"); } else { die("already stopped\r\n"); } }
public function checkRunningCrons() { $entityManager = $this->managerRegistry->getManagerForClass('DspSoftsCronManagerBundle:CronTaskLog'); $cronTaskLogRepo = $entityManager->getRepository('DspSoftsCronManagerBundle:CronTaskLog'); $cronTaskLogs = $cronTaskLogRepo->searchRunning(); foreach ($cronTaskLogs as $cronTaskLog) { if (posix_getpgid($cronTaskLog->getPid()) === false) { if ($this->logger !== null) { $this->logger->info(sprintf('PID %s not found for cron task log id %s, terminating task...', $cronTaskLog->getPid(), $cronTaskLog->getId())); } $cronTaskLog->setStatus(CronTaskLog::STATUS_FAILED); $cronTaskLog->setPid(null); $cronTaskLog->setDateEnd(new \DateTime()); $entityManager->persist($cronTaskLog); $entityManager->flush(); } } }
/** * Poll the sigFile looking for a signal to self-deliver. * This is useful if we don't know the PID of the worker - we can easily deliver signals * if we only know the ClassName and ID of the DataObject. */ public function alarmHandler() { $sigFile = $this->args['sigFile']; if (file_exists($sigFile) && is_readable($sigFile) && is_writable($sigFile)) { $signal = (int) file_get_contents($sigFile); if (is_int($signal) && in_array((int) $signal, [SIGTERM, SIGINT, SIGQUIT, SIGUSR1, SIGUSR2, SIGCONT])) { echo sprintf('[-] Signal "%s" received, delivering to own process group, PID "%s".' . PHP_EOL, $signal, getmypid()); // Mark the signal as received. unlink($sigFile); // Dispatch to own process group. $pgid = posix_getpgid(getmypid()); if ($pgid <= 0) { echo sprintf('[-] Unable to send signal to invalid PGID "%s".' . PHP_EOL, $pgid); } else { posix_kill(-$pgid, $signal); } } } // Wake up again soon. pcntl_alarm(1); }
private function checkExistingInstance() { $pidFile = Config::get('ajumamoro:pid_file', './.ajumamoro.pid'); if (file_exists($pidFile) && is_readable($pidFile)) { $oldPid = file_get_contents($pidFile); if (posix_getpgid($oldPid) === false) { return false; } else { Logger::error("An already running ajumamoro process with pid {$oldPid} detected.\n"); return true; } } else { if (file_exists($pidFile)) { Logger::error("Could not read pid file [{$pidFile}]."); return true; } else { if (is_writable(dirname($pidFile))) { return false; } else { return false; } } } }
/** * @param ConsoleCommandEvent $event * * @return void * @throws CommandAlreadyRunningException */ public function onConsoleCommand(ConsoleCommandEvent $event) { // generate pid file name $commandName = $event->getCommand()->getName(); // check for exceptions if (in_array($commandName, $this->exceptionsList)) { return; } $clearedCommandName = $this->cleanString($commandName); $pidFile = $this->pidFile = $this->pidDirectory . "/{$clearedCommandName}.pid"; // check if command is already executing if (file_exists($pidFile)) { $pidOfRunningCommand = file_get_contents($pidFile); if (posix_getpgid($pidOfRunningCommand) !== false) { throw (new CommandAlreadyRunningException())->setCommandName($commandName)->setPidNumber($pidOfRunningCommand); } // pid file exist but the process is not running anymore unlink($pidFile); } // if is not already executing create pid file file_put_contents($pidFile, getmypid()); // register shutdown function to remove pid file in case of unexpected exit register_shutdown_function(array($this, 'shutDown'), null, $pidFile); }
/** * @param int $wait max time to wait to acquire lock (seconds) * @return bool TRUE if acquired; else false */ public function acquire($wait) { if (!$this->hasDeps()) { return TRUE; } $waitUs = $wait * 1000 * 1000; $totalDelayUs = 0; // total total spent waiting so far (microseconds) $nextDelayUs = 0; while ($totalDelayUs < $waitUs) { if ($nextDelayUs) { usleep($nextDelayUs); $totalDelayUs += $nextDelayUs; } if (!$this->fs->exists($this->lockFile)) { $this->fs->dumpFile($this->lockFile, $this->pid); return TRUE; } $lockPid = (int) trim(file_get_contents($this->lockFile)); if ($lockPid == $this->pid) { return TRUE; } if (!posix_getpgid($lockPid)) { $this->fs->dumpFile($this->lockFile, $this->pid); return TRUE; } $nextDelayUs = rand($this->minDelayUs, min($this->maxDelayUs, $waitUs - $totalDelayUs)); } return FALSE; }
private function annihilateProcessGroup() { $pid = $this->childPID; $pgid = posix_getpgid($pid); if ($pid && $pgid) { // NOTE: On Ubuntu, 'kill' does not recognize the use of "--" to // explicitly delineate PID/PGIDs from signals. We don't actually need it, // so use the implicit "kill -TERM -pgid" form instead of the explicit // "kill -TERM -- -pgid" form. exec("kill -TERM -{$pgid}"); sleep($this->killDelay); // On OSX, we'll get a permission error on stderr if the SIGTERM was // successful in ending the life of the process group, presumably because // all that's left is the daemon itself as a zombie waiting for us to // reap it. However, we still need to issue this command for process // groups that resist SIGTERM. Rather than trying to figure out if the // process group is still around or not, just SIGKILL unconditionally and // ignore any error which may be raised. exec("kill -KILL -{$pgid} 2>/dev/null"); $this->childPID = null; } }
protected function getPid() { $pid_file = config('laravoole.base_config.pid_file'); if (file_exists($pid_file)) { $pid = file_get_contents($pid_file); if (posix_getpgid($pid)) { return $pid; } else { unlink($pid_file); } } return false; }
protected function check_workers() { foreach ($this->consumers as $key => $consumer) { if (posix_getpgid($consumer) === false) { $this->logger->addCritical("Consumer {$this->consumers_id[$consumer]} has shutdown. Restarting it"); unset($this->consumers[$key]); unset($this->consumers_id[$consumer]); array_push($this->consumers, $this->createConsumer(count($this->consumers) + 1)); } } }
public function status() { return posix_getpgid($this->pid) !== false; }
public static function isPIDExists($pid) { return function_exists('posix_getpgid') ? posix_getpgid($pid) !== false : file_exists('/proc/' . $pid); }
public function killChildProcesses() { foreach ($this->childProcesses as $childProcesses) { foreach ($childProcesses as $pid) { exec("kill -15 {$pid}"); while (posix_getpgid($pid) && !exec('cat /proc/' . $pid . '/status | grep zombie')) { sleep(1); } } } }
/** * Get process group id for job control * * @param int $pid The process id. * * @return int */ public function getpgid(int $pid) : int { return posix_getpgid($pid); }
(at your option) any later version. Dash Ninja is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Dash Ninja. If not, see <http://www.gnu.org/licenses/>. */ DEFINE('DMN_VERSION', '0.1.0'); xecho('dmnautoupdate v' . DMN_VERSION . "\n"); function die2($retcode) { unlink(DMN_AUTOUPDATE_SEMAPHORE); die($retcode); } if (file_exists(DMN_AUTOUPDATE_SEMAPHORE) && posix_getpgid(intval(file_get_contents(DMN_AUTOUPDATE_SEMAPHORE))) !== false) { xecho("Already running (PID " . sprintf('%d', file_get_contents(DMN_AUTOUPDATE_SEMAPHORE)) . ")\n"); die(10); } file_put_contents(DMN_AUTOUPDATE_SEMAPHORE, sprintf('%s', getmypid())); xecho("Reading latest version fetched from server: "); if (file_exists("dmnautoupdate.data.json")) { $data = file_get_contents("dmnautoupdate.data.json"); if ($data === FALSE) { echo "ERROR (Could not read file)\n"; die2(1); } $data = json_decode($data, true); if ($data === FALSE) { echo "ERROR (Could not decode JSON data)\n"; die2(1);
/** * Sync users and groups to the local database */ public function sync($output = null) { if (php_sapi_name() !== 'cli') { $path = $this->FreePBX->Config->get("AMPSBIN"); exec($path . "/fwconsole userman sync"); return; } $ASTRUNDIR = \FreePBX::Config()->get("ASTRUNDIR"); $lock = $ASTRUNDIR . "/userman.lock"; $continue = true; if (file_exists($lock)) { $pid = file_get_contents($lock); if (posix_getpgid($pid) !== false) { $continue = false; } else { unlink($lock); } } if ($continue) { $pid = getmypid(); file_put_contents($lock, $pid); $this->connect(); $this->output = $output; $this->out(""); $this->out("Updating All Users"); $this->updateAllUsers(); $this->out("Updating All Groups"); $this->updateAllGroups(); $this->out("Updating Primary Groups"); $this->updatePrimaryGroups(); $this->out("Executing User Manager Hooks"); $this->executeHooks(); unlink($lock); } else { print_r("User Manager is already syncing (Process: " . $pid . ")"); } }
/** * check process is running * @param $pid process id * @return bool if process is running return true otherwise return false */ protected function isProcessRunning($pid) { return !!posix_getpgid($pid); }
$egid = posix_getegid(); echo "egid={$egid}\n"; $groups = posix_getgroups(); echo "groups=\n"; print_r($groups); $login = posix_getlogin(); echo "login={$login}\n"; $pgrp = posix_getpgrp(); echo "pgrp={$pgrp}\n"; $setsid = posix_setsid(); if ($setsid > 0) { echo "posix_setsid succeeded\n"; } else { echo "posix_setsid failed\n"; } $getpgid = posix_getpgid($pid); if ($getpgid > 0) { echo "posix_getpgid succeeded\n"; } else { echo "posix_getpgid failed\n"; } $getsid = posix_getsid($pid); if ($getsid > 0) { echo "posix_getsid succeeded\n"; } else { echo "posix_getsid failed\n"; } $setpgid = posix_setpgid($pid, $getpgid); if ($setpgid > 0) { echo "posix_setpgid succeeded\n"; } else {
private function gracefulProcessGroup() { $pid = $this->childPID; $pgid = posix_getpgid($pid); if ($pid && $pgid) { exec("kill -INT -{$pgid}"); } }
public function isProcessRunning($pid) { return !!posix_getpgid($pid); }
VERIFY(strlen(posix_ctermid())); VERIFY(strlen(posix_getcwd())); $ret = posix_getgrgid(posix_getgid()); VERIFY($ret != false); VERIFY(count((array) $ret) != 0); $bynam = posix_getgrnam($ret['name']); VS($ret, $bynam); $ret = posix_getgrnam("root"); VERIFY($ret != false); VERIFY(count((array) $ret) != 0); $bygid = posix_getgrgid($ret['gid']); VS($ret, $bygid); // $ret = posix_getgroups(); // VERIFY($ret != false); // VERIFY(count((array)$ret) != 0); VERIFY(posix_getpgid(0)); VERIFY(posix_getpgrp()); VERIFY(posix_getpid()); VERIFY(posix_getppid()); $ret = posix_getpwnam("root"); VERIFY($ret != false); VERIFY(count((array) $ret) != 0); VS(posix_getpwnam(""), false); VS(posix_getpwnam(-1), false); $ret = posix_getpwuid(0); VERIFY($ret != false); VERIFY(count((array) $ret) != 0); VS(posix_getpwuid(-1), false); $ret = posix_getrlimit(); VERIFY($ret != false); VERIFY(count((array) $ret) != 0);
/** * checks if the child thread is alive * * @return boolean */ public function isAlive() { if ($this->pid === null) { return false; } $pid = pcntl_waitpid($this->pid, $status, WNOHANG); $alive = $pid === 0; if (!$alive) { $alive = posix_kill($this->pid, 0); } if (!$alive) { $alive = posix_getpgid($this->pid) !== false; } if (!$alive) { $alive = file_exists("/proc/{$this->pid}"); } return $alive; }