2010-03-22 65 views
0

我現在試圖在php中分叉。 我想在子進程中做一些查詢和更新.. 問題是,每當一個子進程完成時,它會關閉連接,使其他查詢失敗。 以下是我的示例代碼!PHP分叉和mysql數據庫連接問題

#!/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! 
    } 
} 
?> 

回答

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

謝謝它適合我! – 2010-03-22 08:29:09