Files
kiri-http-server/Processes/TraitProcess.php
T

106 lines
2.5 KiB
PHP
Raw Normal View History

2024-09-04 09:40:31 +08:00
<?php
namespace Kiri\Server\Processes;
use Exception;
use Kiri;
use Swoole\Process;
2026-07-08 11:39:27 +08:00
use const SIGKILL;
use const SIGTERM;
2024-09-04 09:40:31 +08:00
trait TraitProcess
{
/**
* @var array
*/
private array $_process = [];
/**
* @param string|array|AbstractProcess $class
* @return void
* @throws
*/
public function addProcess(string|array|AbstractProcess $class): void
{
2024-09-04 11:21:12 +08:00
if (!is_array($class)) $class = [$class];
2024-09-04 09:40:31 +08:00
foreach ($class as $name) {
2024-09-04 11:21:12 +08:00
if (is_string($name)) $name = Kiri::getDi()->get($name);
2024-09-04 09:40:31 +08:00
if (isset($this->_process[$name->getName()])) {
throw new Exception('AbstractProcess(' . $name->getName() . ') is exists.');
}
2024-09-04 11:21:12 +08:00
$this->_process[$name->getName()] = $this->genProcess($name);
2024-09-04 09:40:31 +08:00
}
}
/**
* @param AbstractProcess $name
* @return Process
*/
private function genProcess(AbstractProcess $name): Process
{
return new Process(function (Process $process) use ($name) {
2025-12-18 15:39:40 +08:00
$process->name('[' . \config('site.id', 'system-service') . '].' . $name->getName() . '[' . $process->pid . ']');
2024-09-04 09:40:31 +08:00
$name->onShutdown($process)->process($process);
},
$name->getRedirectStdinAndStdout(),
$name->getPipeType(),
$name->isEnableCoroutine());
}
/**
* @param string $name
* @return AbstractProcess|null
*/
public function getProcess(string $name): ?Process
{
return $this->_process[$name] ?? null;
}
/**
* @return array
*/
public function getProcesses(): array
{
return $this->_process;
}
2026-07-08 11:39:27 +08:00
/**
* @return void
*/
private function terminateProcesses(): void
{
$pids = [];
foreach ($this->_process as $process) {
$pid = (int)($process->pid ?? 0);
if ($pid > 1 && $pid !== getmypid()) {
$pids[] = $pid;
}
}
$pids = array_values(array_unique($pids));
foreach ($pids as $pid) {
if (@Process::kill($pid, 0)) {
@Process::kill($pid, SIGTERM);
}
}
for ($i = 0; $i < 10; $i++) {
$alive = array_values(array_filter($pids, static fn(int $pid): bool => @Process::kill($pid, 0)));
if ($alive === []) {
return;
}
usleep(100000);
}
foreach ($pids as $pid) {
if (@Process::kill($pid, 0)) {
@Process::kill($pid, SIGKILL);
}
}
}
}