Question

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

Was it helpful?

Solution

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

           fork()
      +------+-----+
    child    |   parent
-------------+------------
> echo $pid  | > echo $pid
0            | 4650

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top