tewilove
tewilove

Reputation: 41

Call pcntl_fork twice cause PHP CGI dead loop

function spawn($exec, $args = array()) {
$pid = pcntl_fork();
if ($pid < 0)
    return false;
else if ($pid == 0) {
    $ppid = getmypid();
    $pid = pcntl_fork();
    if ($pid < 0)
        file_put_contents('/tmp/error.log', "fork failed: ${cmd} ". implode(' ', $args). "\n");
    else if ($pid == 0) {
        pcntl_waitpid($ppid, $status);
        pcntl_exec($exec, $args);
    }
    else
        exit(0);
    }
}

This works well in CLI mode. But for php-fpm it causes the caller dead loop and then a timeout. Why this happens?

Upvotes: 2

Views: 717

Answers (2)

user149341
user149341

Reputation:

It doesn't work because calling exit() under FPM doesn't cause the parent process to exit -- it just makes it clean up the request, then return to the pool of available worker processes. Since it never actually exits, the pcntl_waitpid ends up waiting forever.

As Roman Newaza notes, you should really avoid the pcntl functions under FPM (and, in general, outside CLI).

Upvotes: 1

Roman Newaza
Roman Newaza

Reputation: 11690

Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment: PCNTL/Introduction

Upvotes: 0

Related Questions