通过管道(pipe)实现多进程通信交换hello world内容

知识点:

#include <unistd.h>

int pipe (int pipedes[2]) ;

pipedes[0]  ---> 通过管道接收数据时使用的文件描述符,管道的出口;

pipedes[1]  ---> 通过管道传输数据时使用的文件描述符,管道的入口。

用例:

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

#define BUF_SIZE 30

int main(int argc, char const *argv[])
{
    char str[] = "Hello World!";
    char buf[BUF_SIZE];
    
    int fds[2];
    pipe(fds);

    pid_t pid = fork();
    if (pid == 0)
    {
        write(fds[1], str, sizeof(str));
    }
    else
    {
        read(fds[0], buf, BUF_SIZE);
        puts(buf);
    }

    return 0;
}

输出:

猜你喜欢

转载自blog.csdn.net/xunye_dream/article/details/109412178