Skip to content

Commit

Permalink
feat: add ProcessUtil kill pid tree
Browse files Browse the repository at this point in the history
  • Loading branch information
kocoten1992 committed Aug 11, 2023
1 parent 4b57a16 commit 07196a3
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/ProcessUtil.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Talmp\Phputils;

class ProcessUtil
{
public static function killTree(int $pid): void
{
$pstree_output = exec("pstree -p -A $pid");

// php(2065)---sh(2069)---php7.3(2070)
// will matches [2065, 2069, 2070]
preg_match_all('/(?<=\()\d+(?=\)(?=-|$))/', $pstree_output, $matches);

foreach ($matches[0] as $match) {
posix_kill($match, SIGKILL);
}
}
}
45 changes: 45 additions & 0 deletions tests/ProcessUtilTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

use PHPUnit\Framework\TestCase;
use Talmp\Phputils\ProcessUtil;

class ProcessUtilTest extends TestCase
{
public function test_kill_tree(): void
{
$process = proc_open(
'php -r "exec(\'sleep 60\');"',
[STDIN, STDOUT, STDOUT],
$pipes
);

$process_status = proc_get_status($process);

$this->assertTrue(file_exists('/proc/'.$process_status['pid']));

exec('kill -0 '.$process_status['pid'], $output, $exit_code);

$this->assertEquals(0, $exit_code);

$this->assertNotFalse(posix_getpgid($process_status['pid']));

$time_start = time();

ProcessUtil::killTree($process_status['pid']);

while (true) {
$process_status = proc_get_status($process);

if ($process_status['running'] === false) {
break;
}
}

$this->assertFalse($process_status['running']);
$this->assertEquals(-1, $process_status['exitcode']);

$time_end = time();

$this->assertTrue($time_end - $time_start < 60);
}
}

0 comments on commit 07196a3

Please sign in to comment.