我现在正试图在php中进行分叉。 我想在子进程中进行一些查询和更新.. 问题是每当子进程完成时,它会关闭连接,这会导致其他查询失败。 以下是我的示例代码!!
#!/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!
}
}
?>
答案 0 :(得分:2)
尽量不要在父进程中打开另一个SQL连接,并在每个具有不同链接标识符变量的子线程中创建另一个指向MySQL的链接。
<?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);
}
}
?>