使用 mkfifo 函数创建命名管道(FIFO),并在两个进程之间进行通信

在 C++ 中使用 mkfifo 函数创建命名管道(FIFO),并在两个进程之间进行通信。

步骤

  1. 创建命名管道:使用 mkfifo 函数创建命名管道。
  2. 打开管道:在读取和写入进程中打开管道。
  3. 读取和写入数据:一个进程向管道写入数据,另一个进程从管道读取数据。

写入进程代码 (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

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值