tags:

views:

48

answers:

1

I am now trying to do forking in php. I would like to do some query and update in child process.. the problem is that whenever a child process finish, it close the connection which makes the other queries fail. The following is my sample code!!

#!/usr/local/bin/php
<?php
set_time_limit(0); # forever program!
$db = mysql_connect("server","user","pwd");
mysql_select_db("schema",$db);
$sql = "query";
$res = mysql_query($sql,$db);
while($rows = mysql_fetch_array($res)) {
  $rv = pcntl_fork();
  if($rv == -1){
    echo "forking failed";
  }
  elseif($rv){
    echo "parent process $rv\n";
    $db = mysql_connect("server","user","pwd",true);
    mysql_select_db("schema",$db);
  }
  else{
    echo "child process $rv\n";
    $sql1 = "another query";
    $res1 = mysql_query($sql1,$db);
    while($messages = mysql_fetch_array($res1)) {
      $sql2 = "update query";
      mysql_query($sql2,$db);
    }
    exit(0);
    //it terminates both child process and mysql connection!
  }
}
?>
+1  A: 

Try not to open another SQL connection in parent process, and create another link to MySQL in each child thread with different link identifier variable.

<?php
  set_time_limit(0); # forever program! 
  $db = mysql_connect("server","user","pwd"); 
  mysql_select_db("schema",$db); 
  $sql = "query"; 
  $res = mysql_query($sql,$db); 
  while($rows = mysql_fetch_array($res)) { 
    $rv = pcntl_fork(); 
    if($rv == -1){ 
      echo "forking failed"; 
    }
    elseif($rv){ 
      echo "parent process $rv\n"; 
      // do nothing with connection here, use old one ($db)
    }
    else
    { 
      $db2 = mysql_connect("server","user","pwd", true); 
      echo "child process $rv\n"; 
      $sql1 = "another query"; 
      $res1 = mysql_query($sql1,$db2); 
      while($messages = mysql_fetch_array($res1)) { 
        $sql2 = "update query"; mysql_query($sql2,$db2); 
      } 
      exit(0); 
    } 
} 
?>
Olegas
Thanks it works for me!
Soe Naung Win