Send a Signal to a worker system process

@since  1.2.0
@return void
321613
public function sendSignal($options)
    {
        $this->outputTitle($options->title);

        $force = $this->input->getOption('force')->value;
        $all = $this->input->getOption('all')->value;

        if ($force) {
            $this->debug("'FORCE' option detected");
        }

        if ($all) {
            $this->debug("'ALL' option detected");
        }

        if (!isset($options->formatListItem)) {
            $resqueStats = $this->ResqueStats;
            $ResqueStatus = $this->ResqueStatus;
            $fresque = $this;
            $listFormatter = function ($worker) use ($resqueStats, $ResqueStatus, $fresque) {
                return sprintf(
                    '%s, started %s ago',
                    $ResqueStatus->isSchedulerWorker($worker) ? '**Scheduler Worker**' : $worker,
                    $fresque->formatDateDiff(call_user_func_array(array($resqueStats, 'getWorkerStartDate'), array($worker)))
                );
            };
        } else {
            $listFormatter = $option->formatListItem;
        }

        if (empty($options->workers)) {
            $this->output->outputLine($options->noWorkersMessage, 'failure');
        } else {
            sort($options->workers);
            $this->debug('Found ' . $options->getWorkersCount() . ' workers');

            $workerIndex = array();
            if (!$all && $options->getWorkersCount() > 1) {
                $i = 1;
                $menuItems = array();
                foreach ($options->workers as $worker) {
                    $menuItems[$i++] = $listFormatter($worker);
                }

                $menuItems['all'] = $options->allOption;

                $index = $this->getUserChoice(
                    $options->listTitle,
                    $options->selectMessage . ':',
                    $menuItems
                );

                if ($index === 'all') {
                    $workerIndex = range(1, $options->getWorkersCount());
                } else {
                    $workerIndex[] = $index;
                }

            } else {
                $workerIndex = range(1, $options->getWorkersCount());
            }

            foreach ($workerIndex as $index) {
                $worker = $options->workers[$index - 1];

                list($hostname, $pid, $queue) = explode(':', (string)$worker);

                $this->debug('Sending -' . $options->signal . ' signal to process ID ' . $pid);

                if ($this->runtime['Scheduler']['enabled'] === true && $this->ResqueStatus->isSchedulerWorker($worker)) {
                    if (isset($options->schedulerWorkerAction)) {
                        $f = $options->schedulerWorkerAction;
                        $f($worker);
                    }
                    $this->output->outputText($options->schedulerWorkerActionMessage . ' ... ');
                } else {
                    $this->output->outputText($options->actionMessage . ' ' . $pid . ' ... ');
                }



                $killResponse = $this->kill($options->signal, $pid);
                $options->onSuccess($pid, (string)$worker);

                if ($killResponse['code'] === 0) {
                    $this->output->outputLine('Done', 'success');
                } else {
                    $this->output->outputLine($killResponse['message'], 'failure');
                }
            }
        }

        $this->output->outputLine();
    }
518958
private function connected() : void
    {
        $this->connected = true;
        while ($this->buffer) {
            $this->client->send(array_shift($this->buffer));
        }
    }
1215509
private function startProcess(): void
    {
        $this->process = proc_open($this->command, static::DESCRIPTOR_SPEC, $this->pipes, $this->cwd);

        foreach ($this->pipes as $pipe) {
            stream_set_blocking($pipe, false);
        }
    }
782630
public function selectAndProcess(): void
    {
        $read = $this->resources;
        $unused_write = null;
        $unsued_exception = null;

        stream_select(
            $read,
            $unused_write,
            $unused_exception,
            $this->options['timeout_select'],
            $this->options['timeout_select_microsec']
        );

        foreach ($read as $socket) {
            if ($socket == $this->socket->getResource()) {
                $this->processMasterSocket();
            } else {
                $this->processClientSocket($socket);
            }
        }
    }
1358181
protected function listenForSignals()
    {
        pcntl_async_signals(true);

        pcntl_signal(SIGTERM, function () {
            $this->shouldQuit = true;
        });

        pcntl_signal(SIGUSR2, function () {
            $this->paused = true;
        });

        pcntl_signal(SIGCONT, function () {
            $this->paused = false;
        });
    }
386254
protected function registerSignalHandlers(): bool
    {
        if (!function_exists('pcntl_signal')) {
            $this->log->warning('Signal Handling is not supported on this system');

            return false;
        }

        pcntl_async_signals(true);

        pcntl_signal(SIGTERM, [$this, 'shutdownNow']);
        pcntl_signal(SIGINT, [$this, 'shutdownNow']);
        pcntl_signal(SIGQUIT, [$this, 'shutdown']);
        pcntl_signal(SIGUSR1, [$this, 'killChild']);
        pcntl_signal(SIGUSR2, [$this, 'pauseProcessing']);
        pcntl_signal(SIGCONT, [$this, 'continueProcessing']);

        $this->log->debug('Registered Signals');

        return true;
    }
729747
public function sigWakeUp()
    {
        $this->log('SIGPIPE received; attempting to wake up', Logger::DEBUG);
        $this->redis->establishConnection();

        Event::fire(Event::WORKER_WAKEUP, $this);
    }
721712
public function run()
    {
        //Update process state.
        static::$_status = static::STATUS_RUNNING;

        // Register shutdown function for checking errors.
        register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));

        // Set autoload root path.
        Autoloader::setRootPath($this->_autoloadRootPath);

        // Create a global event loop.
        if (!static::$globalEvent) {
            $event_loop_class = static::getEventLoopName();
            static::$globalEvent = new $event_loop_class;
            $this->resumeAccept();
        }

        // Reinstall signal.
        static::reinstallSignal();

        // Init Timer.
        Timer::init(static::$globalEvent);

        // Set an empty onMessage callback.
        if (empty($this->onMessage)) {
            $this->onMessage = function () {};
        }

        restore_error_handler();
        
        // Try to emit onWorkerStart callback.
        if ($this->onWorkerStart) {
            try {
                call_user_func($this->onWorkerStart, $this);
            } catch (\Exception $e) {
                static::log($e);
                // Avoid rapid infinite loop exit.
                sleep(1);
                exit(250);
            } catch (\Error $e) {
                static::log($e);
                // Avoid rapid infinite loop exit.
                sleep(1);
                exit(250);
            }
        }

        // Main loop.
        static::$globalEvent->loop();
    }
320095
public function run()
    {
        $this->setupSignalHandlers();

        $procs = [];
        while (true) {
            $jobs = $this->runner->getJobs();
            foreach ($jobs as $job) {
                if (! array_key_exists($job->identifier(), $procs)) {
                    $procs[$job->identifier()] = [];
                }
                while (count($procs[$job->identifier()]) > $job->numWorkers()) {
                    // Stopping an excessive child.
                    echo 'Stopping an excessive child.' . PHP_EOL;
                    $proc = array_pop($procs[$job->identifier()]);
                    $status = proc_get_status($proc);
                    // Keep sending SIGTERM until the child exits.
                    while ($status['running'] === true) {
                        @proc_terminate($proc);
                        usleep(50000);
                        $status = proc_get_status($proc);
                    }
                    @proc_close($proc);
                }
                for ($i = 0; $i < $job->numWorkers(); $i++) {
                    $needStart = false;
                    if (array_key_exists($i, $procs[$job->identifier()])) {
                        $status = proc_get_status($procs[$job->identifier()][$i]);
                        if ($status['running'] !== true) {
                            $needStart = true;
                        }
                    } else {
                        $needStart = true;
                    }
                    if ($needStart) {
                        echo 'Starting a child.' . PHP_EOL;
                        $procs[$job->identifier()][$i] = proc_open(
                            sprintf('%s %d', $this->command, $job->id()),
                            $this->descriptorSpec,
                            $pipes
                        );
                    }
                }
            }
            usleep(1000000); // Reload the config after 1 second
            pcntl_signal_dispatch();
            if ($this->shutdown) {
                echo 'Shutting down, waiting for the children' . PHP_EOL;
                foreach ($procs as $k => $v) {
                    foreach ($v as $proc) {
                        $status = proc_get_status($proc);
                        // Keep sending SIGTERM until the child exits.
                        while ($status['running'] === true) {
                            @proc_terminate($proc);
                            usleep(50000);
                            $status = proc_get_status($proc);
                        }
                        @proc_close($proc);
                    }
                }
                echo 'BatchDaemon exiting' . PHP_EOL;
                exit;
            }
            // Reload the config
            $this->runner->loadConfig();
        }
    }
946778
public function signal(int $signo)
    {
        if (!$this->isRunning()) {
            throw new StatusError('The process is not running.');
        }

        proc_terminate($this->process, (int) $signo);
    }
286184
protected function loop(): void
    {
        $job = $this->getJob();

        if (!$job) {
            $this->sleep();

            return;
        }

        $this->log->info(sprintf('got Job %s', $job->getId()));

        $this->getEventManager()->trigger('beforeFork', $job);
        $this->setWorkingOn($job);

        $this->child = $this->fork();

        // We are the Child Process
        if ($this->child === 0 || $this->child === false) {
            $this->runAsChild($job);
        }

        // We are the parent Process
        if ($this->child > 0) {
            $this->runAsParent($job);
        }

        $this->child = null;
        $this->finishedWorking();
    }
86882
public function process()
    {
        if ($this->worker->getState() == Worker::INVALID) {
            throw new \RuntimeException('Invalid state to process.');
        }

        $expiry = 5000 + $this->delay;
        if ($this->worker->isExpired($expiry)) {
            $this->getLogger()->debug('Worker is expired, no longer registered to workerhandler.');
            $this->worker->setState(Worker::INVALID);

            return;
        }

        try {
            $read = $write = array();
            $this->getPoller()->poll($read, $write, 100);
        } catch (\ZMQPollException $ex) {
            pcntl_signal_dispatch();

            return;
        }

        $this->workerHandlerStream->handle();
        $this->serviceStream->handle();
        $this->handleResult();
        $this->heartbeat();
        pcntl_signal_dispatch();
    }
1069362
public function signal($signal)
    {
        // Log all signals sent to the daemon.
        $this->getLogger()->debug('Received signal: ' . $signal);

        // Let's make sure we have an application instance.
        if (!is_subclass_of($this, __CLASS__)) {
            $this->getLogger()->emergency('Cannot find the application instance.');

            throw new \RuntimeException('Cannot find the application instance.');
        }

        // @event onReceiveSignal

        switch ($signal) {
            case SIGINT:
            case SIGTERM:
                // Handle shutdown tasks
                if ($this->running && $this->isActive()) {
                    $this->shutdown();
                } else {
                    $this->close();
                }

                break;

            case SIGHUP:
                // Handle restart tasks
                if ($this->running && $this->isActive()) {
                    $this->shutdown(true);
                } else {
                    $this->close();
                }

                break;

            case SIGCHLD:
                // A child process has died
                while ($this->pcntlWait($signal, WNOHANG || WUNTRACED) > 0) {
                    usleep(1000);
                }

                break;

            case SIGCLD:
                while ($this->pcntlWait($signal, WNOHANG) > 0) {
                    $signal = $this->pcntlChildExitStatus($signal);
                }

                break;

            default:
                break;
        }
    }
1288782
def send_signal(self, request, response, forum):
        
        self.view_signal.send(
            sender=self, forum=forum, user=request.user, request=request, response=response,
        )
518728
public function signalHandler($signo)
    {
        switch ($signo) {
            case SIGTERM:
                $this->output->writeln("<fg=red>Got SIGTERM.</fg=red>");
                $this->shutdown();
                exit;

            case SIGINT:
                $this->output->writeln("<fg=red>Got SIGINT.</fg=red>");
                $this->shutdown();
                exit;
        }
    }
795824
public function emit(Signal $signal)
    {
        if ($this->transactionDepth === 0) {
            $this->signalDispatcher->emit($signal);
        } else {
            $this->signalsQueue[$this->transactionCount][] = $signal;
        }
    }
1078668
protected function sigterm()
    {
        if (Daemon::$config->logsignals->value) {
            $this->log('Caught SIGTERM.');
        }

        $this->signalToChildren(SIGTERM);
        $this->shutdown(SIGTERM);
    }