1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace PjbServer\Tools\System\Linux; |
6
|
|
|
|
7
|
|
|
use PjbServer\Tools\Exception; |
8
|
|
|
use PjbServer\Tools\System\ProcessInterface; |
9
|
|
|
use Psr\Log\LoggerInterface; |
10
|
|
|
use Psr\Log\NullLogger; |
11
|
|
|
|
12
|
|
|
class LinuxProcess implements ProcessInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var LoggerInterface |
16
|
|
|
*/ |
17
|
|
|
protected $logger; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* LinuxProcess constructor. |
21
|
|
|
*/ |
22
|
28 |
|
public function __construct(?LoggerInterface $logger = null) |
23
|
|
|
{ |
24
|
28 |
|
if ($logger === null) { |
25
|
3 |
|
$logger = new NullLogger(); |
26
|
3 |
|
} |
27
|
28 |
|
$this->logger = $logger; |
28
|
28 |
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Check whether a pid is running. |
32
|
|
|
* |
33
|
|
|
* @throws Exception\InvalidArgumentException |
34
|
|
|
* |
35
|
|
|
* @param int $pid |
36
|
|
|
* |
37
|
|
|
* @return bool |
38
|
|
|
*/ |
39
|
18 |
|
public function isRunning(int $pid): bool |
40
|
|
|
{ |
41
|
18 |
|
$cmd = sprintf('kill -0 %d 2>&1', $pid); |
42
|
18 |
|
$this->logger->debug(__METHOD__ . ": Exec command: $cmd"); |
43
|
18 |
|
exec($cmd, $output, $return_var); |
44
|
18 |
|
|
45
|
|
|
return $return_var === 0; |
46
|
18 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Kill a process. |
50
|
|
|
* |
51
|
|
|
* @throws Exception\InvalidArgumentException |
52
|
|
|
*/ |
53
|
|
|
public function kill(int $pid, bool $wait = false): bool |
54
|
|
|
{ |
55
|
|
|
$killed = false; |
56
|
|
|
if ($this->isRunning($pid)) { |
57
|
|
|
if ($wait) { |
58
|
|
|
$sleep_time = '0.2'; |
59
|
15 |
|
$cmd = sprintf('kill %d; while ps -p %d; do sleep %s;done;', $pid, $pid, $sleep_time); |
60
|
|
|
$this->logger->debug(__METHOD__ . " Exec command: $cmd"); |
61
|
15 |
|
exec($cmd, $output, $return_var); |
62
|
15 |
|
$killed = ($return_var === 0); |
63
|
14 |
|
if ($killed) { |
64
|
14 |
|
$this->logger->debug(__METHOD__ . " Successfully killed process {$pid}"); |
65
|
14 |
|
} else { |
66
|
14 |
|
$this->logger->notice(__METHOD__ . " Cannot kill process {$pid}, $output"); |
67
|
14 |
|
} |
68
|
14 |
|
} else { |
69
|
14 |
|
//@todo |
70
|
14 |
|
throw new \Exception('@todo Only wait=true is supported for now'); |
71
|
14 |
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
14 |
|
return $killed; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|