Ram
Ram

Reputation: 1193

PHP pcntl_wait() does not wait for child exit

I have a php script that forks and parent calls pnctl_wait(). According to php manual pcntl_wait() should suspend execution of the current process until a child has exited. But this does not happen. The parent process does not wait at all and executes the next line immediately.

I have tried to replicate the issue in a small sample script below

<?php
$parentpid=getmypid();
declare(ticks=1);
$apid = pcntl_fork();
if ($apid == -1) {
  die('could not fork for client '.$client);
 } else if ($apid) {     //parent                                                                                                              


pcntl_wait($status,WNOHANG); //Protect against Zombie children                                                                     
/* Parent does not wait here */ 

  print "PARENT $parentpid has forked $apid \n";   

  sleep(100);
 } else { // child                                                                                                                             
  $pid = getmypid();
  print "CHILD $pid  is sleeping\n";
  sleep(40);
 }


?>

Upvotes: 0

Views: 2740

Answers (2)

Nabeel Perwaiz
Nabeel Perwaiz

Reputation: 393

Note, pcntl in php functions will not work on apache server running, So PHP don't support child processes like other languages such as fork in C++.

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157947

You don't want the option WNOHANG here. Just use:

pcntl_wait($status);

If you pass WNOHANG pcntl_wait() will not wait for children to return. It only reports childs which have already been terminated.


The whole example should look like this:

$parentpid = getmypid();
$apid = pcntl_fork();

if ($apid == -1) {
  die('could not fork for client '.$client);
} else if ($apid) {
    // Parent process
    print "PARENT $parentpid has forked $apid \n";

    // Wait for children to return. Otherwise they 
    // would turn into "Zombie" processes
    pcntl_wait($status);
} else {
  // Child process
  $pid = getmypid();
  print "CHILD $pid  is sleeping\n";
  sleep(40);
}

Upvotes: 3

Related Questions