文章目錄
- 🚀 深入理解命名管道(FIFO)及其C++實現
- 一、命名管道核心特性
- 1.1 🧩 基本概念
- 二、💻 代碼實現解析
- 2.1 📁 公共頭文件(common.hpp)
- 2.2 🖥? 服務器端(server.cpp)
- 2.3 📱 客戶端(client.cpp)
- 三、🔧 運行機制圖解
- 四、💡 技術亮點分析
- 4.1 🚦 阻塞行為控制
- 4.2 ? 數據傳輸特性
- 4.3 🐛 錯誤處理策略
- 五、🚀 編譯運行演示
- 5.1 🔧 操作流程

🚀 深入理解命名管道(FIFO)及其C++實現
一、命名管道核心特性
1.1 🧩 基本概念
命名管道(FIFO)是一種特殊的文件類型,具有以下特點:
- 跨進程通信:允許無親緣關系進程通信 🌐
- 文件系統可見:通過
mkfifo
創建實體文件 📂 - 雙工限制:需分別以讀/寫模式打開文件描述符 🔄
- 阻塞特性:打開操作會阻塞直到另一端就緒 ?
二、💻 代碼實現解析
2.1 📁 公共頭文件(common.hpp)
#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>#define FIFO_FILE "./myfifo" // 🚪 管道文件路徑
#define MODE 0664 // 🔒 權限模式enum {FIFO_CREATE_ERR = 1, // 🛠? 創建錯誤FIFO_DELETE_ERR = 2, // 🗑? 刪除錯誤FIFO_OPEN_ERROR = 3 // 🔓 打開錯誤
};class Init { // 🔄 RAII管理管道生命周期
public:Init() {int n = mkfifo(FIFO_FILE, MODE);if(n == -1) {perror("? mkfifo");exit(FIFO_CREATE_ERR);}}~Init() {int m = unlink(FIFO_FILE);if(m == -1) {perror("? unlink");exit(FIFO_DELETE_ERR);}}
};
2.2 🖥? 服務器端(server.cpp)
#include "common.hpp"int main() {Init init; // 🏗? 自動創建管道int fd = open(FIFO_FILE, O_RDONLY); // ?? 阻塞直到客戶端連接if(fd < 0) {perror(" open");exit(FIFO_OPEN_ERROR);}cout << " Server ready" << endl;while(true) {char buffer[1024];int bytes = read(fd, buffer, sizeof(buffer)-1);if(bytes > 0) {buffer[bytes] = '\0';cout << " Received: " << buffer << endl;} else if(bytes == 0) {cout << " Client disconnected" << endl;break;} else {perror(" read");break;}}close(fd);return 0;
}
2.3 📱 客戶端(client.cpp)
#include "common.hpp"int main() {int fd = open(FIFO_FILE, O_WRONLY); // 🔔 觸發服務器喚醒if(fd < 0) {perror(" open");exit(FIFO_OPEN_ERROR);}cout << " Connected to server" << endl;string line;while(getline(cin, line)) {write(fd, line.c_str(), line.size()); // 📤 發送數據}close(fd);return 0;
}
三、🔧 運行機制圖解
四、💡 技術亮點分析
4.1 🚦 阻塞行為控制
// 服務器端 open() 阻塞示例
int fd = open(FIFO_FILE, O_RDONLY); // ??// 客戶端 open() 解除阻塞
int fd = open(FIFO_FILE, O_WRONLY); // ??
4.2 ? 數據傳輸特性
特性 | 描述 | 圖標 |
---|---|---|
字節流傳輸 | 無消息邊界,需自定義協議 | 🌊 |
原子性保證 | 小于PIPE_BUF(通常4K)保證原子性 | ?? |
流量控制 | 寫滿緩沖區后自動阻塞 | 🚧 |
4.3 🐛 錯誤處理策略
if(write(fd, buf, len) == -1) {if(errno == EPIPE) { // 💔 連接斷開cout << " Connection closed" << endl;close(fd);exit(1);}perror(" write");
}
五、🚀 編譯運行演示
5.1 🔧 操作流程
# 終端1:啟動服務器
$ ./server
🔄 Server ready# 終端2:啟動客戶端
$ ./client
💬 Please Enter@ Hello World!# 終端1顯示
📥 Received: Hello World!