php - Need explanation pcnt_fork()

30

I am new to pcnt_fork,

<?php
  $pid = pcntl_fork();
  echo $pid;
  if($pid) {
  // parent process runs what is here
  echo "-parent\n";
   }
  else {
  // child process runs what is here
  echo "-child\n";
  } ?>

ouptut : 25347-parent 0-child

my question is , here $pid will be the process id of the child process i.e 25347 right? then it should echo only parent then why its also giving 0-child as a output...can anyone explain

955

Answer

Solution:

This is what the state looks like after a fork operation:

           fork()
      +------+-----+
    child    |   parent
553

Answer

---+
708

Answer

-- > echo $pid | > echo $pid 0 | 4650
459

Answer

Solution:

pcntl-fork (just like fork) forks a child but it doesn't closes the parent.

In the end you have 2 running processes, the parent and the child.

The 2 lines of print that you are receiving come from 2 different processes: the parent that has received the pid of the child and the child itself.

341

Answer

Solution:

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.

People are also looking for solutions to the problem: php - Model Factory returning the age of based on the birthdate just like this

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.