Question

I want to run parallel processes to process at least 4 users simultaneously.

ob_end_flush();

for($i = 0; $i < 4; $i++)
{
   $pid=pcntl_fork();
   if ($pid == -1) {
      echo("Could not create a new child.");
      exit;
   } else if ($pid == 0) {
      //This will get excuted only in the child process
      echo 'parent1';
      sleep(5);
      echo 'parent2';
     exit;
   }
}

The output is something like this:

> php testscript.php
parent1
parent1
parent1
parent1
> parent2
parent2
parent2
parent2

What is currently happening is after displaying parent1 4 times the control on the script is lost, and a new empty command line is started. After waiting for 5 more seconds the remaining output comes.

How can i avoid that from happening. I want to be able to break the script as and when I want.

EDIT

If i send a signal via terminal say by pressing CTRL+C, the script does not stops, need a way to inform the script to stop at that instant.

Was it helpful?

Solution

You are creating dirty zombie/parent-less processes who're being adopted by others who certainly don't want them either =)

When you're working with forking you need to understand you're creating a copy of the current process (stack/heap and all), giving it a new process id (PID) and setting it's parent id (PPID) as its own as to say the spawned process is a child. Here the parent of these 4 new children finished all his apparent work then died without any error because he has nothing left to do.. But as any respectful parent should do, your parent process should sit around and take care of his children. That's where signals can become useful especially the SIGCHLD signal, which will be sent to any parent process whos child just past away. Combining that with a small event handling loop and your parent can gracefully manage his children \o/

tl;dr I have a an example fork wrapper sitting in my blog http://codehackit.blogspot.be/2012/01/childpids-break-pcntlsignaldispatch.html

OTHER TIPS

you need to use pcntl_signal to set up a signal handler for CTRL-C(which equals to SIGINT, with a value of 2) if you want to react on it in a custom fashion.

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