Completed
Push — master ( 8da12a...178c32 )
by Sébastien
14:05 queued 11:13
created

LinuxProcess   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 93.1%

Importance

Changes 0
Metric Value
wmc 7
c 0
b 0
f 0
lcom 0
cbo 2
dl 0
loc 73
ccs 27
cts 29
cp 0.931
rs 10

3 Methods

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