在 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.

最低0.47元/天 解锁文章
566

被折叠的 条评论
为什么被折叠?



