管道
管道是比較常用的多進程通信手段,管道分爲無名管道與有名管道,無名管道只能用於具有親緣關係的進程間通信,而有名管道可以用於同一主機上任意進程。
理解
爲了方便理解,可以將管道比作文件,進程A將數據寫到管道P中,然後進程B從管道P中讀取數據。php提供的管道操作API與操作文件的API基本一樣,除了創建管道使用posix_mkfifo函數,讀寫等操作均與文件操作函數相同。當然,你可以直接使用文件模擬管道,但是那樣無法使用管道的特性了。
代碼
// 定義管道路徑,與創建管道
$pipe_path = './test.pipe';
if(!file_exists($pipe_path)){
if(!posix_mkfifo($pipe_path,0664)){
exit("create pipe error!");
}
}
$pid = pcntl_fork();
if($pid == 0){
// 子進程,向管道寫數據
$file = fopen($pipe_path,'w');
while (true){
fwrite($file,'hello world');
$rand = rand(1,3);
sleep($rand);
}
exit("child end!\n");
}else{
// 父進程,從管道讀數據
$file = fopen($pipe_path,'r');
while (true){
$rel = fread($file,11);
echo "{$rel}\n";
$rand = rand(1,2);
sleep($rand);
}
}
運行結果