|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | +/** |
| 5 | + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors |
| 6 | + * SPDX-License-Identifier: AGPL-3.0-or-later |
| 7 | + */ |
| 8 | + |
| 9 | +namespace OCA\Libresign\Service\Process; |
| 10 | + |
| 11 | +use Psr\Log\LoggerInterface; |
| 12 | + |
| 13 | +class ProcessSignaler { |
| 14 | + public function __construct( |
| 15 | + private LoggerInterface $logger, |
| 16 | + ) { |
| 17 | + } |
| 18 | + |
| 19 | + public function isRunning(int $pid): bool { |
| 20 | + if ($pid <= 0) { |
| 21 | + return false; |
| 22 | + } |
| 23 | + |
| 24 | + if (function_exists('posix_kill')) { |
| 25 | + return @posix_kill($pid, 0); |
| 26 | + } |
| 27 | + |
| 28 | + if (!function_exists('exec')) { |
| 29 | + return false; |
| 30 | + } |
| 31 | + |
| 32 | + try { |
| 33 | + exec(sprintf('kill -0 %d 2>/dev/null', $pid), $output, $exitCode); |
| 34 | + return $exitCode === 0; |
| 35 | + } catch (\Throwable $e) { |
| 36 | + $this->logger->debug('Failed to probe process status', [ |
| 37 | + 'pid' => $pid, |
| 38 | + 'error' => $e->getMessage(), |
| 39 | + ]); |
| 40 | + return false; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public function stopPid(int $pid, int $signal = SIGTERM): bool { |
| 45 | + if ($pid <= 0) { |
| 46 | + return false; |
| 47 | + } |
| 48 | + |
| 49 | + if (function_exists('posix_kill')) { |
| 50 | + return @posix_kill($pid, $signal); |
| 51 | + } |
| 52 | + |
| 53 | + if (!function_exists('exec')) { |
| 54 | + return false; |
| 55 | + } |
| 56 | + |
| 57 | + try { |
| 58 | + exec(sprintf('kill -%d %d 2>/dev/null', $signal, $pid), $output, $exitCode); |
| 59 | + return $exitCode === 0; |
| 60 | + } catch (\Throwable $e) { |
| 61 | + $this->logger->debug('Failed to terminate process', [ |
| 62 | + 'pid' => $pid, |
| 63 | + 'signal' => $signal, |
| 64 | + 'error' => $e->getMessage(), |
| 65 | + ]); |
| 66 | + return false; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments