通过单管道(pipe)实现两个进程间双向通信

用例:

#include <stdio.h>
#include <unistd.h>

#define BUF_SIZE 30

int main(int argc, char const *argv[])
{
    
    
    char req[] = "Who are you?";
    char rsp[] = "I'm xunye.";

    char buf[BUF_SIZE];

    int fds[2];
    pipe(fds);

    pid_t pid = fork();
    if (pid == 0)
    {
    
    
        write(fds[1], req, sizeof(req));   // 子进程写入数据
        sleep(2);     // 防止子进程写入管道的数据被自己读取了。
        read(fds[0], buf, BUF_SIZE);   // 子进程读取父进程写入的数据
        printf("Child proc output: %s\n", buf);
    }
    else
    {
    
    
        read(fds[0], buf, BUF_SIZE);   // 父进程读取子进程写入的数据
        printf("Parent proc output: %s\n", buf);
        write(fds[1], rsp, sizeof(rsp)); // 父进程写入数据
        sleep(3);   // 防止父进程先退出
    }

    return 0;
}

执行输出结果:在这里插入图片描述
【注】通过单管道实现两个进程间通信时存在缺陷:
需要确定好各进程间数据的读写时机,通过上述代码中子进程代码部分的sleep使用可以佐证。

解决方法可以采用两个管道实现两个进程间的通信。

猜你喜欢

转载自blog.csdn.net/xunye_dream/article/details/109412580
今日推荐