H
H
HellWalk2021-01-22 18:02:34
PHP
HellWalk, 2021-01-22 18:02:34

What changes how pcntl_fork works in PHPUnit?

Let's take a pure php script with the following code:

$sleep = 3;
$pid = pcntl_fork();

if ($pid === -1) {
    echo 'Не удалось породить дочерний процесс' . PHP_EOL;
    die();
}

if ($pid) {
    echo 'PID: ' . $pid . PHP_EOL;
    echo "Ожидаем $sleep секунды и убиваем дочерний процесс" . PHP_EOL;
    sleep($sleep);
    echo 'Убиваем дочерний процесс' . PHP_EOL;
    posix_kill($pid, SIGKILL);
    echo 'End' . PHP_EOL;
} else {
    echo '[Дочерний код работает]' . PHP_EOL;
    sleep(300);
}


By executing it, we get the following result:


PID: 57237 Wait
3 seconds and kill child process
[Child code running]
Kill child process
End


After that, let's create a simple unit test with the same code:

public function testFork(): void
    {
        $sleep = 3;
        $pid = pcntl_fork();

        if ($pid === -1) {
            echo 'Не удалось породить дочерний процесс' . PHP_EOL;
            die();
        }

        if ($pid) {
            echo 'PID: ' . $pid . PHP_EOL;
            echo "Ожидаем $sleep секунды и убиваем дочерний процесс" . PHP_EOL;
            sleep($sleep);
            echo 'Убиваем дочерний процесс' . PHP_EOL;
            posix_kill($pid, SIGKILL);
            echo 'End' . PHP_EOL;
        } else {
            echo '[Дочерний код работает]' . PHP_EOL;
            sleep(300);
        }
    }


We execute it and get:


PID: 57335 Wait
3 seconds and kill child process
Kill child process
End


As you can see, the child process did not work. Actually the question is - what in phpunit changes the work with process forks?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
neol, 2021-01-22
@HellWalk

phpunit buffers output and this buffering is not thread ready. Your stream is running, it's just that the output is lost. If you disable buffering, it will take off:

ob_end_flush();
if ($pid) {
    echo 'PID: ' . $pid . PHP_EOL;
    echo "Ожидаем $sleep секунды и убиваем дочерний процесс" . PHP_EOL;
    sleep($sleep);
    echo 'Убиваем дочерний процесс' . PHP_EOL;
    posix_kill($pid, SIGKILL);
    echo 'End' . PHP_EOL;
} else {
    echo '[Дочерний код работает]' . PHP_EOL;
    sleep(300);
}

M
mitaichik, 2017-06-08
@NikkyNick1

This happens when servers\patch-mapping are not configured - PhpStorm stops executions on the first line of code.
You need to configure the seover and set the paths to match: Settings -> Language & Framworks -> PHP -> Servers
https://www.jetbrains.com/help/phpstorm/creating-a...

N
Nikolai Konyukhov, 2017-06-08
@heahoh

Just like not in Yii2.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question