1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PjbServer\Tools\System\Linux; |
4
|
|
|
|
5
|
|
|
use PjbServer\Tools\Exception; |
6
|
|
|
use PjbServer\Tools\System\ProcessInterface; |
7
|
|
|
use Psr\Log\LoggerInterface; |
8
|
|
|
use Psr\Log\NullLogger; |
9
|
|
|
|
10
|
|
|
class LinuxProcess implements ProcessInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var LoggerInterface |
14
|
|
|
*/ |
15
|
|
|
protected $logger; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* LinuxProcess constructor. |
19
|
|
|
* |
20
|
|
|
* @param LoggerInterface $logger |
21
|
|
|
*/ |
22
|
28 |
|
public function __construct($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($pid) |
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 |
|
$running = ($return_var === 0); |
45
|
|
|
|
46
|
18 |
|
return $running; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Kill a process. |
51
|
|
|
* |
52
|
|
|
* @throws Exception\InvalidArgumentException |
53
|
|
|
* |
54
|
|
|
* @param int $pid |
55
|
|
|
* @param bool $wait wait for the process to be killed |
56
|
|
|
* |
57
|
|
|
* @return bool |
58
|
|
|
*/ |
59
|
15 |
|
public function kill($pid, $wait = false) |
60
|
|
|
{ |
61
|
15 |
|
$killed = false; |
62
|
15 |
|
if ($this->isRunning($pid)) { |
63
|
14 |
|
if ($wait) { |
64
|
14 |
|
$sleep_time = '0.2'; |
65
|
14 |
|
$cmd = sprintf('kill %d; while ps -p %d; do sleep %s;done;', $pid, $pid, $sleep_time); |
66
|
14 |
|
$this->logger->debug(__METHOD__ . " Exec command: $cmd"); |
67
|
14 |
|
exec($cmd, $output, $return_var); |
68
|
14 |
|
$killed = ($return_var === 0); |
69
|
14 |
|
if ($killed) { |
70
|
14 |
|
$this->logger->debug(__METHOD__ . " Successfully killed process {$pid}"); |
71
|
14 |
|
} else { |
72
|
|
|
$this->logger->notice(__METHOD__ . " Cannot kill process {$pid}, $output"); |
73
|
|
|
} |
74
|
14 |
|
} else { |
75
|
|
|
//@todo |
76
|
|
|
throw new \Exception('@todo Only wait=true is supported for now'); |
77
|
|
|
} |
78
|
14 |
|
} |
79
|
|
|
|
80
|
15 |
|
return $killed; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|