I am trying to use a pcntl
extetntion for PHP
to run some methods of my CLI
class in a new thread. I wrote a small test method:
private function startProcess($data)
{
$this->log('Start a child process');
$pid = pcntl_fork();
if($pid == -1)
$this->log('Could not fork');
elseif($pid)
pcntl_wait($status);
else {
$this->process($data);
sleep(10);
posix_kill(posix_setsid(), SIGTERM);
}
}
This method is called 10 times. $this->process($data);
just prints the data in the console. As i understood it should start 10 processes and print my data, after it exit. But instead i get to wait 10 seconds for each message. Where i'm wrong?
You are waiting for each process to complete immediately after starting it. If you really want to run 10 at a time, don't wait until you started all 10.
for($i = 0; $i < 10; $i++)
startProcess(...);
for($i = 0; $i < 10; $i++)
pcntl_wait($status);
private function startProcess($data)
{
$this->log('Start a child process');
$pid = pcntl_fork();
if($pid == -1)
$this->log('Could not fork');
elseif(!$pid) {
$this->process($data);
sleep(10);
posix_kill(posix_setsid(), SIGTERM);
}
}