LinuxProcess   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 96.15%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 24
c 1
b 0
f 0
dl 0
loc 63
ccs 25
cts 26
cp 0.9615
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isRunning() 0 7 1
A kill() 0 22 4
A __construct() 0 6 2
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