PHP 進程間通信(IPC)常用方式包括管道、消息隊列、共享內存、Socket。本文深入講解匿名管道/命名管道(FIFO)在 PHP 中的實現,並封裝一個 Pipe 類,實現進程間雙向數據傳輸。
ulimit -p 查看)。stream_set_blocking($fp, 0) 設置非阻塞。<?php
class Pipe {
public $fifoPath;
private $w_pipe;
private $r_pipe;
public function __construct($name = 'pipe', $mode = 0666) {
$this->fifoPath = "/tmp/$name." . posix_getpid();
if (!file_exists($this->fifoPath)) {
if (!posix_mkfifo($this->fifoPath, $mode)) {
throw new Exception("Create pipe failed: $name");
}
} else {
throw new Exception("Pipe already exists: $name");
}
}
// --- 寫端操作 ---
public function openWrite() {
$this->w_pipe = fopen($this->fifoPath, 'w');
if (!$this->w_pipe) throw new Exception("Open write failed");
return true;
}
public function write($data) { return fwrite($this->w_pipe, $data); }
public function writeAll($data) {
$fp = fopen($this->fifoPath, 'w');
fwrite($fp, $data);
fclose($fp);
}
public function closeWrite() { return fclose($this->w_pipe); }
// --- 讀端操作 ---
public function openRead() {
$this->r_pipe = fopen($this->fifoPath, 'r');
if (!$this->r_pipe) throw new Exception("Open read failed");
return true;
}
public function read($bytes = 1024) { return fread($this->r_pipe, $bytes); }
public function readAll() {
$fp = fopen($this->fifoPath, 'r');
$data = '';
while (!feof($fp)) $data .= fread($fp, 1024);
fclose($fp);
return $data;
}
public function closeRead() { return fclose($this->r_pipe); }
// 刪除管道文件
public function remove() { return unlink($this->fifoPath); }
}
?>
<?php
$pipe = new Pipe('test_pipe');
$pid = pcntl_fork();
if ($pid == -1) die('fork failed');
if ($pid > 0) {
// 父進程:寫入數據
$pipe->openWrite();
for ($i = 0; $i < 5; $i++) {
$msg = "Parent msg $i\n";
$pipe->write($msg);
echo "Parent sent: $msg";
sleep(1);
}
$pipe->closeWrite();
pcntl_wait($status);
$pipe->remove();
} else {
// 子進程:讀取數據
$pipe->openRead();
while (($line = $pipe->read(1024)) !== '') {
echo "Child received: $line";
}
$pipe->closeRead();
exit(0);
}
?>
stream_set_blocking($pipe->r_pipe, 0) 配合 stream_select 實現多路複用。posix_mkfifo,需改用 proc_open 的管道描述符或 COM 組件。remove() 避免殘留臨時文件。管道是 PHP 多進程通信的輕量級方案,適合父子進程、數據流傳輸場景。Pipe 類封裝了創建、讀寫、銷毀全生命周期,便於在項目中復用。理解阻塞機制與緩衝區限制是避免死鎖的關鍵。