2
我需要在後臺啓動一些php腳本(無需等待),然後等到所有進程終止,類似於屏障的東西(如果您熟悉多線程)。Php腳本同步
例子:
//...code...
run_script('myscript1.php');//it's like an exec but doesen't wait for the script to finish
run_script('myscript2.php');//it's like an exec but doesen't wait for the script to finish
run_script('myscript3.php');//it's like an exec but doesen't wait for the script to finish
do_something();
wait_until_all_proc_are_finished();//it will wait until all script are executed
do_something_else();
//....
我創建了一個腳本,應該做的伎倆;我在控制檯測試它和它的作品不錯,但它doesen't在PHP頁面的工作,我不明白爲什麼!
class TSync{
private $threads=array();
function tcreate($p){
$tname=tempnam(null,'THS_');//create a temp name
$p=addslashes($p);//just to be sure
$name=addslashes($tname);
$ex= 'php -r "$fp=fopen(\''.$name.'\',\'r+\');flock($fp,LOCK_EX);include(\''.$p.'\');fclose($fp);"';
run_on_background($ex);//execute it on background
$this->threads[count($this->threads)]=$tname;
return count($this->threads)-1;//returns the thread "id"
}
function twait($id){
$f=$this->threads[$id];//recover the name
/***even this doesen't work***
$fp=fopen($f,'r');
flock($fp,LOCK_EX);
fclose($fp);
*/
echo date("H:i:s"),"#Locking on $f<br/>";
$ex= 'php -r "$fp=fopen(\''.$f.'\',\'r\');flock($fp,LOCK_EX);fclose($fp);"';
exec($ex);
unlink($f);
}
}
$t=new TSync();//create the class
$f=$t->tcreate(dirname(__FILE__).'/testth.php');//this is a test script that waits 10s
$t->twait($f);//now you should wait the script,commenting this line should result on the script not waiting
在控制檯上推出有效的代碼示例(在Windows上進行測試)
start /b php.exe -r "$fp=fopen('C:\\Windows\\Temp\\THS6D7.tmp','w');flock($fp,LOCK_EX);include('C:/.../testth.php');fclose($fp);"
如果我的代碼多次推出第二腳本將等待第一所以它應該工作。
所以究竟是什麼你問什麼來解決這個問題? – 2011-04-08 23:17:09
問爲什麼它不起作用時,在網頁的上下文(而不是CLI) – Ben 2011-04-08 23:31:56
本是正確的: 我貼的代碼應該做我所問,但在PHP doesen't工作,我不知道爲什麼; 如果你可以修復它或發佈一些其他的解決方案,請做。 無論如何,我最近發現我使用的PHP版本(5.3.0)在fclose上解鎖資源(php> 5.3.2 doesen't不再那麼做),我不知道更新是否可以修復它。 – Plokko 2011-04-09 08:07:51