开发者

PHP forking and mysql database connection problem

开发者 https://www.devze.com 2022-12-23 22:22 出处:网络
I am now trying to do forking in php. I would like to do some query and upd开发者_Python百科ate in child process..

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

精彩评论

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

关注公众号