0

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?

Kin
  • 4,466
  • 13
  • 54
  • 106
  • `pcntl_wait` makes the parent process wait for the child one to return the status. Your child does something then waits 10 seconds. The parent won't do anything until the child has exited (which you do with posix_kill). What do you want to accomplish? – N.B. Jul 16 '13 at 12:50

1 Answers1

2

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);
    }
}
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
  • @Kirix - if you don't understand something, please say what you don't understand, typing ??? makes you look dumb. This answer is the only proper one, he's launching 10 processes first and then in another block waits for their exit statuses. You weren't doing that. If you need clarification on what each function does, please say so like a normal, intelligent human being. – N.B. Jul 16 '13 at 12:51
  • @N.B. it was before he edited your answer. So tried it, but it becomes a zombie process. https://www.dropbox.com/s/wc6owbk8qf19kyy/php_zombie.jpg – Kin Jul 16 '13 at 12:54
  • @Kirix - may I suggest using threads if you want to achieve parallel processing? – N.B. Jul 16 '13 at 12:56
  • It's been there for quite some time.. :) – N.B. Jul 16 '13 at 13:01
  • @N.B. just tried it and i'm very sad.. It's not included by default in php so it wont work on production servers. – Kin Jul 16 '13 at 13:04
  • If you are at the stage of writing CLI scripts, then I'm sure you can upgrade PHP to support pthreads. It's one of the biggest advantages of PHP as a scripting language - it's extensible via extensions. If you're trying to implement parallel processing of a web request, then neither forking or threading are the answers. You'd need a job queue for that. – N.B. Jul 16 '13 at 13:10