萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 多進程編程:管道通信原理與類封裝

前言

PHP 進程間通信(IPC)常用方式包括管道、消息隊列、共享內存、Socket。本文深入講解匿名管道/命名管道(FIFO)在 PHP 中的實現,並封裝一個 Pipe 類,實現進程間雙向數據傳輸。

管道基礎概念

  • 本質:內核維護的環形緩衝區,默認 4KB(可通過 ulimit -p 查看)。
  • 特性:半雙工、固定大小、讀寫阻塞(默認)、遵循先進先出(FIFO)。
  • 阻塞行為:寫入時滿則阻塞;讀取時空則阻塞。可用 stream_set_blocking($fp, 0) 設置非阻塞。

Pipe 類完整實現

<?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 實現多路複用。
  • 雙向通信:需創建兩個管道(或使用 Socket Pair),一個父寫子讀,一個子寫父讀。
  • Windows 兼容:Windows 不支持 posix_mkfifo,需改用 proc_open 的管道描述符或 COM 組件。
  • 資源清理:進程異常退出時確保調用 remove() 避免殘留臨時文件。

總結

管道是 PHP 多進程通信的輕量級方案,適合父子進程、數據流傳輸場景。Pipe 類封裝了創建、讀寫、銷毀全生命周期,便於在項目中復用。理解阻塞機制與緩衝區限制是避免死鎖的關鍵。

copyright © 萬盛學電腦網 all rights reserved