• 进程间通信pipe和fifo


    注:fifo和pipe可以像普通的文件描述符一样读写,但不可以进行定位操作

    具体参考:https://blog.csdn.net/sdkdlwk/article/details/79765676

    mkfifo()

    //创建有名管道(FIFO special file),创建完了就像普通文件一样open(),再读写,成描述符功返回0,失败返回-1设errno。VS$man 3 mkfifo
    #include <sys/types.h>
    #include <sys/stat.h>
    int mkfifo(const char *pathname, mode_t mode);

    pathname:the FIFO special file's name

    mode :the FIFO's permissions.

    //创建FIFO管道文件
    int res=mkfifo(“./a.fifo”,0664);
    if(-1==res)
        perror("mkfifo"),exit(-1);
    res=open(“./a.fifo”,O_RDONLY);
    if(-1==res)
        perror(“open”),exit(-1);

    pipe()

    //创建无名管道,相当于直接把open()返回的fd直接放到形参中,而不需额外的变量接收管道文件的描述符,用于父子进程间通过管道进行IPC通信,,成功返回0,失败返回-1设errno
    #include <unistd.h>
    int pipe(int pipefd[2]);    //代码自注释,表示它需要的参数是一个有两个元素的数组,如果虽然作为形参,实质上和int* pipefd没有区别

    pipefd :return two fds referring to the ends of the pipe.

    • pipefd[0] :read end,读端
    • pipefd[1] :write end,读端.

    fork()创建的child也会文件描述符总表也会复制一份So,对于child, 应该先关闭读端, 再写,对于parent,应该先关闭写端, 再读

    //使用pipe()实现父子进程的通信
    #include<unistd.h>
    #include<sys/types.h>
    #include<sys/stat.h>
    #include<stdlib.h>
    #include<stdio.h>
    int main(){
        //1. 创建无名管道
        int pipefd[2];
        int res=pipe(pipefd);
        if(-1==res)
            perror("pipe"),exit(-1);
        //2. 创建子进程
        pid_t pid=fork();
        if(-1==pid)
            perror("fork"),exit(-1);
    
        //3. 子进程开始启动,写入1~100;
        if(0==pid){
            close(pipefd[0]);
            int i=0;
            for(i=1;i<=100;i++){
                write(pipefd[1],&i,sizeof(int));
            }
            close(pipefd[1]);//关闭写端
            exit(0);
        }
        
        //4. 父进程开始启动,读取管道中的数据
        close(pipefd[1]);
        int i=0;
        for(i=1;i<=100;i++){
            int x=0;
            read(pipefd[0],&x,sizeof(int));
            printf("%d ",x);
        }
        printf("
    ");
        close(pipefd[0]);
        return 0;
    }
  • 相关阅读:
    Linux (Ubuntu)安装ssh
    Linux (Ubuntu)提示ifconfig:找不到命令
    Docker介绍
    微服务用到的技术
    移动端BI的设计
    Cobbler Web管理(二)
    基于CentOS7环境下的Cobbler部署介绍(一)
    使用google-perftools优化nginx内存管理提升性能
    解决 nginx 配置TLS1.2无效,总是TLS1.0的问题
    在nginx中将爬虫过来的请求转到指定的后端服务
  • 原文地址:https://www.cnblogs.com/FREMONT/p/9828891.html
Copyright © 2020-2023  润新知