Checks if given process is active and valid (by checking worker name).

@param int $pid
@param string $workerName
@return bool
771863
protected function pidIsValid(int $pid, string $workerName) : bool
    {
        $processInfo = exec(sprintf('ps -p %d -o args=', $pid));
        if (empty($processInfo)) {
            return false;
        }
        if (strpos($processInfo, $workerName) === false) {
            return false;
        }
        return true;
    }
867117
public static boolean isProcessRunning(String baseDir)
    {
        File pidFile = new File(baseDir, "pid");
        boolean exists = pidFile.isFile();
        return exists;
    }
140088
public function kill(int $pid, bool $wait = false): bool
    {
        $killed = false;
        if ($this->isRunning($pid)) {
            if ($wait) {
                $sleep_time = '0.2';
                $cmd = sprintf('kill %d; while ps -p %d; do sleep %s;done;', $pid, $pid, $sleep_time);
                $this->logger->debug(__METHOD__ . " Exec command: $cmd");
                exec($cmd, $output, $return_var);
                $killed = ($return_var === 0);
                if ($killed) {
                    $this->logger->debug(__METHOD__ . " Successfully killed process {$pid}");
                } else {
                    $this->logger->notice(__METHOD__ . " Cannot kill process {$pid}, $output");
                }
            } else {
                //@todo
                throw new \Exception('@todo Only wait=true is supported for now');
            }
        }

        return $killed;
    }
5980
function delThread(pid) {
    //Delete worker entry from worker

    delete workers[pid];

    //Remove pid from pid array
    var position = pids.indexOf(pid);
    if (~position) pids.splice(position, 1);

    //Reset array index
    pids = pids.filter(function(){return true;});
}
52736
public function wait($pid = null)
    {
        if ($pid) {
            $threads = [$pid];
        } else {
            $threads = $this->threads;
        }

        $error = false;
        $status = 0;
        foreach ($threads as $pid) {
            pcntl_waitpid($pid, $status);
            if ($status > 0) {
                $error = $status;
            }
            unset($this->threads[$pid]);
        }

        if (!$this->ignoreErrors && $error) {
            $memory = shmop_open($this->memoryKey, "a", 0, 0);
            $errors = shmop_read($memory, 0, static::SHARED_MEMORY_LIMIT);
            shmop_delete($memory);
            shmop_close($memory);

            $error = "An error occurred within a thread, the return code was (" . $error . ")";
            if ($errors = trim($errors)) {
                $error .= "\n" . $errors;
            }
            throw new \Exception($error);
        }

        return $status;
    }
1152873
public function stopWorker(int $workerId = null): bool
    {
        if ($this->server) {
            return $this->server->stop($workerId);
        }

        return false;
    }
49294
public function kill_process($pid)
    {

        if (!is_numeric($pid)) return false;
        $pid = (int)$pid;
        $sql = "KILL $pid";

        return $this->db->query($sql);
    }
683583
protected function launchWorker(): bool {
        $this->log(LogLevel::DEBUG, "[{pid}]   launching fleet worker");

        // Prepare current state prior to forking
        $workerConfig = $this->payloadExec('getWorkerConfig');
        if ($workerConfig === false) {
            $this->log(LogLevel::DEBUG, "[{pid}]    launch cancelled by payload");
            return false;
        }

        $this->fork('fleet', $workerConfig);

        // Return daemon thread
        if ($this->realm != 'worker') {
            return true;
        }

        /*
         *
         * WORKER THREADS BELOW
         *
         */

        // Unhandle SIGINT, SIGTERM, SIGCHLD
        pcntl_signal(SIGINT, SIG_DFL);
        pcntl_signal(SIGTERM, SIG_DFL);
        pcntl_signal(SIGCHLD, SIG_DFL);

        // Move handling of SIGHUP, SIGUSR1, SIGUSR2 to workerSignal()
        pcntl_signal(SIGHUP, [$this, 'workerSignal']);
        pcntl_signal(SIGUSR1, [$this, 'workerSignal']);
        pcntl_signal(SIGUSR2, [$this, 'workerSignal']);

        $exitCode = $this->runPayloadApplication($workerConfig);
        exit($exitCode);
    }
329909
def _is_pid_running_on_windows(pid):
    
    import ctypes.wintypes

    kernel32 = ctypes.windll.kernel32
    handle = kernel32.OpenProcess(1, 0, pid)
    if handle == 0:
        return False
    exit_code = ctypes.wintypes.DWORD()
    ret = kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code))
    is_alive = (ret == 0 or exit_code.value == _STILL_ALIVE)  # pylint: disable=undefined-variable
    kernel32.CloseHandle(handle)
    return is_alive
516030
public static function isProcessEventGenerator(WorkerInterface $worker) : bool
    {
        try{
            $method = new \ReflectionMethod($worker, 'processEvent');

            return $method->isGenerator();
        }
        catch(\ReflectionException $e)
        {
            return false;
        }
    }
933178
public function endProcess($pid) {
		if (!$pid) {
			return;
		}

		$QueueProcesses = TableRegistry::get('Queue.QueueProcesses');
		/** @var \Queue\Model\Entity\QueueProcess $queuedProcess */
		$queuedProcess = $QueueProcesses->find()->where(['pid' => $pid])->firstOrFail();
		$queuedProcess->terminate = true;
		$QueueProcesses->saveOrFail($queuedProcess);
	}
1013708
public static function checkWorkerStatusForWindows()
    {
        foreach(static::$_processForWindows as $process_data)
        {
            $process = $process_data[0];
            $start_file = $process_data[1];
            $timer_id = $process_data[2];
            $status = proc_get_status($process);
            if(isset($status['running']))
            {
                if(!$status['running'])
                {
                    static::safeEcho("process $start_file terminated and try to restart\n");
                    Timer::del($timer_id);
                    proc_close($process);
                    static::forkOneWorkerForWindows($start_file);
                }
            }
            else
            {
                static::safeEcho("proc_get_status fail\n");
            }
        }
    }
710759
protected static function monitorWorkersForLinux()
    {
        static::$_status = static::STATUS_RUNNING;
        while (1) {
            // Calls signal handlers for pending signals.
            pcntl_signal_dispatch();
            // Suspends execution of the current process until a child has exited, or until a signal is delivered
            $status = 0;
            $pid    = pcntl_wait($status, WUNTRACED);
            // Calls signal handlers for pending signals again.
            pcntl_signal_dispatch();
            // If a child has already exited.
            if ($pid > 0) {
                // Find out witch worker process exited.
                foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
                    if (isset($worker_pid_array[$pid])) {
                        $worker = static::$_workers[$worker_id];
                        // Exit status.
                        if ($status !== 0) {
                            static::log("worker[" . $worker->name . ":$pid] exit with status $status");
                        }

                        // For Statistics.
                        if (!isset(static::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
                            static::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
                        }
                        static::$_globalStatistics['worker_exit_info'][$worker_id][$status]++;

                        // Clear process data.
                        unset(static::$_pidMap[$worker_id][$pid]);

                        // Mark id is available.
                        $id                              = static::getId($worker_id, $pid);
                        static::$_idMap[$worker_id][$id] = 0;

                        break;
                    }
                }
                // Is still running state then fork a new worker process.
                if (static::$_status !== static::STATUS_SHUTDOWN) {
                    static::forkWorkers();
                    // If reloading continue.
                    if (isset(static::$_pidsToRestart[$pid])) {
                        unset(static::$_pidsToRestart[$pid]);
                        static::reload();
                    }
                }
            }

            // If shutdown state and all child processes exited then master process exit.
            if (static::$_status === static::STATUS_SHUTDOWN && !static::getAllWorkerPids()) {
                static::exitAndClearAll();
            }
        }
    }
722936
protected function _checkStartedWorker($pidFile)
    {
        $pid = false;
        if (file_exists($pidFile) && false !== $pid = file_get_contents($pidFile)) {
            unlink($pidFile);

            return (int)$pid;
        }

        return false;
    }
419774
public static function killAndWait($pid, $signal = SIGTERM, $name = 'process', $waitTime = 30)
    {
        // do stop
        if (!self::kill($signal)) {
            Cli::stderr("Send stop signal to the $name(PID:$pid) failed!");

            return false;
        }

        // not wait, only send signal
        if ($waitTime <= 0) {
            Cli::stdout("The $name process stopped");

            return true;
        }

        $startTime = time();
        Cli::stdout('Stopping .', false);

        // wait exit
        while (true) {
            if (!self::isRunning($pid)) {
                break;
            }

            if (time() - $startTime > $waitTime) {
                Cli::stderr("Stop the $name(PID:$pid) failed(timeout)!");
                break;
            }

            Cli::stdout('.', false);
            sleep(1);
        }

        return true;
    }
35381
protected function validate_workers() {

        $this->load_workers();

        if (empty($this->functions)) {
            $this->log("No workers found");
            posix_kill($this->parent_pid, SIGUSR1);
            exit();
        }

        $this->validate_lib_workers();

        /**
         * Since we got here, all must be ok, send a CONTINUE
         */
        $this->log("Helper is running. Sending continue to $this->parent_pid.", GearmanManager::LOG_LEVEL_DEBUG);
        posix_kill($this->parent_pid, SIGCONT);

        if ($this->check_code) {
            $this->log("Running loop to check for new code", self::LOG_LEVEL_DEBUG);
            $last_check_time = 0;
            while (1) {
                $max_time = 0;
                foreach ($this->functions as $name => $func) {
                    clearstatcache();
                    $mtime = filemtime($func['path']);
                    $max_time = max($max_time, $mtime);
                    $this->log("{$func['path']} - $mtime $last_check_time", self::LOG_LEVEL_CRAZY);
                    if ($last_check_time!=0 && $mtime > $last_check_time) {
                        $this->log("New code found. Sending SIGHUP", self::LOG_LEVEL_PROC_INFO);
                        posix_kill($this->parent_pid, SIGHUP);
                        break;
                    }
                }
                $last_check_time = $max_time;
                sleep(5);
            }
        } else {
            exit();
        }

    }
1103387
public function isRunning($pid)
    {
        $output = $exitCode = null;
        exec(sprintf("ps %d", $pid), $output, $exitCode);
        return $exitCode === 0;
    }