在 C++ 中使用 mkfifo 函数创建命名管道(FIFO),并在两个进程之间进行通信。
步骤
- 创建命名管道:使用 mkfifo 函数创建命名管道。
- 打开管道:在读取和写入进程中打开管道。
- 读取和写入数据:一个进程向管道写入数据,另一个进程从管道读取数据。
写入进程代码 (writer.cpp)
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
int main() {
const char* fifoFile = "/tmp/myfifo"; // 命名管道的路径
// 创建命名管道
mkfifo(fifoFile, 0666);
// 打开命名管道进行写入
int fd = open(fifoFile, O_WRONLY);
// 写入数据到命名管道
const char* message = "Hello from writer process!";
write(fd, message, strlen(message) + 1);
close(fd);
std::cout << "Writer process wrote: " << message << std::endl;
return 0;
}
读取进程代码 (reader.cpp)
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
int main() {
const char* fifoFile = "/tmp/myfifo"; // 命名管道的路径
// 打开命名管道进行读取
int fd = open(fifoFile, O_RDONLY);
// 读取数据
char buffer[256];
read(fd, buffer, sizeof(buffer));
close(fd);
std::cout << "Reader process read: " << buffer << std::endl;
return 0;
}
编译和运行
- 编译
g++ writer.cpp -o writer
g++ reader.cpp -o reader
- 运行
./reader
./writer