David
David

Reputation: 271

Using pcntl library in PHP

I've tried to use the pcntl library in order to fork a child process in php. Here's the simple piece of code I have:

  $pid = pcntl_fork();
  if ($pid != -1) {
    if ($pid) {
       print "In the parent: child PID is $pid\n";
       pcntl_waitpid($pid, $status);
       echo "Back in parent\n";
    } 
    else {
        print "In the child\n";
        exit(19);
    }
   } 
   else {
        echo "Fork failed!\n";
   }

I get the result:

In the child

which means that the parent didn't do anything or maybe somehow the child erased what the parent did (I don't know why..)

If I comment the line: pcntl_waitpid($pid, $status); I get the following result:

In the parent: child PID is 11394 Back in parent

In this case, the child didn't do anything.. How can this happen ? I don't understand how this works.. By the way, I'm working on XAMPP. Could anyone give me some insights ?

Thank you very much!

Upvotes: 2

Views: 1859

Answers (1)

A. R. Younce
A. R. Younce

Reputation: 1923

When run with the latest version of PHP (5.3.5) your example works as posted. Keep in mind that this is with the command line binary. If you are running PHP as an Apache module then you should not be using the pcntl functions.

The output I got was (the pid will be different for you):

In the parent: child PID is 4759
In the child
Back in parent

Upvotes: 2

Related Questions