|
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
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @var LoggerInterface |
|
16
|
|
|
*/ |
|
17
|
|
|
protected $logger; |
|
18
|
|
|
|
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* LinuxProcess constructor. |
|
22
|
|
|
* @param LoggerInterface $logger |
|
23
|
|
|
*/ |
|
24
|
27 |
|
public function __construct($logger = null) |
|
25
|
|
|
{ |
|
26
|
27 |
|
if ($logger === null) { |
|
27
|
3 |
|
$logger = new NullLogger(); |
|
28
|
3 |
|
} |
|
29
|
27 |
|
$this->logger = $logger; |
|
30
|
27 |
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Check whether a pid is running |
|
34
|
|
|
* |
|
35
|
|
|
* @throws Exception\InvalidArgumentException |
|
36
|
|
|
* @param int $pid |
|
37
|
|
|
* @return boolean |
|
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
|
18 |
|
return $running; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* Kill a process |
|
50
|
|
|
* |
|
51
|
|
|
* @throws Exception\InvalidArgumentException |
|
52
|
|
|
* @param int $pid |
|
53
|
|
|
* @param bool $wait wait for the process to be killed |
|
54
|
|
|
* @return bool |
|
55
|
|
|
*/ |
|
56
|
15 |
|
public function kill($pid, $wait = false) |
|
57
|
|
|
{ |
|
58
|
15 |
|
$killed = false; |
|
59
|
15 |
|
if ($this->isRunning($pid)) { |
|
60
|
14 |
|
if ($wait) { |
|
61
|
14 |
|
$sleep_time = '0.2'; |
|
62
|
14 |
|
$cmd = sprintf("kill %d; while ps -p %d; do sleep %s;done;", $pid, $pid, $sleep_time); |
|
63
|
14 |
|
$this->logger->debug(__METHOD__ . " Exec command: $cmd"); |
|
64
|
14 |
|
exec($cmd, $output, $return_var); |
|
65
|
14 |
|
$killed = ($return_var === 0); |
|
66
|
14 |
|
if ($killed) { |
|
67
|
14 |
|
$this->logger->debug(__METHOD__ . " Successfully killed process {$pid}"); |
|
68
|
14 |
|
} else { |
|
69
|
|
|
$this->logger->notice(__METHOD__ . " Cannot kill process {$pid}, $output"); |
|
70
|
|
|
} |
|
71
|
14 |
|
} else { |
|
72
|
|
|
//@todo |
|
73
|
|
|
throw new \Exception("@todo Only wait=true is supported for now"); |
|
74
|
|
|
} |
|
75
|
14 |
|
} |
|
76
|
15 |
|
return $killed; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|