美文网首页
Linux系统调用pipe(无名/匿名管道)

Linux系统调用pipe(无名/匿名管道)

作者: 艾满 | 来源:发表于2021-07-16 16:08 被阅读0次
    //pipe.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/types.h> //基本系统数据类型,是Unix/Linux系统的基本系统数据类型的头文件,含有size_t,time_t,pid_t等类型。
    
    int main(int argc, char const *argv[])
    {
        int result = -1;
        //fd[2]是创建管道的两个文件描述符,一个是读端,一个是写端;fd不是固定的,可写成任意的数组名,比如aa[2]等
        int fd[2],nbytes;
        pid_t pid;
        char string[] = "hello world,my pipe!";
        char readbuffer[100];
        
        //无名管道:没有文件名,只有标识符,fd[0]用来读 fd[1]用来写;无名管道主要用于亲缘进程间的通信
        int *write_fd = &fd[1];
        int *read_fd =&fd[0];
    
        result = pipe(fd);//创建管道,在内核缓冲区会有一个句柄;数组名也是地址
        if (-1 == result)
        {
            printf("创建管道失败!\n");
            return -1;
        }
    
        pid = fork();//创建一个子进程
        if (-1 == pid)
        {
            printf("创建进程失败!\n");
            return -1;
        }else if(0 == pid){//子进程,返回值为0
            close(*read_fd);
            result = write(*write_fd,string,strlen(string));//子进程写
            return 0;
        }else{//父进程返回值为子进程的进程id
            close(*write_fd);
            nbytes = read(*read_fd,readbuffer,sizeof(readbuffer));//父进程读
            printf("父级读到%d bytes data:%s\n",nbytes,readbuffer);
        }
        return 0;
    }
    

    执行结果:


    image.png

    相关文章

      网友评论

          本文标题:Linux系统调用pipe(无名/匿名管道)

          本文链接:https://www.haomeiwen.com/subject/tijbpltx.html