Realize two-way communication between two processes through a single pipe

example:

#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;
}

Execution output result: Insert picture description here
[Note] There are defects in the communication between two processes through a single pipe: it is
necessary to determine the timing of reading and writing data between each process, which can be proved by the use of sleep in the sub-process code part of the above code.

The solution can be to use two pipes to achieve communication between two processes.

Guess you like

Origin blog.csdn.net/xunye_dream/article/details/109412580