开发者

PHP forking and mysql database connection problem

I am now trying to do forking in php. I would like to do some query and upd开发者_Python百科ate 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!
  }
}
?>


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); 
    } 
} 
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜