• LINUX创建管道文件


    两个进程的通信:1、管道文件;2、select 多路复用;

    ps -elf  //查看系统进程

    管道,半双工,一端写一端读

    创建管道文件

    mkfifo 1.pipe



    Makefile
    a:a.c b.c
              gcc a.c -o a
              gcc b.c -o b
    .PHONY:clean
    clean:
              rm a b

    a.c b.c
    #include<sys/types.h>
    #include<sys/stat.h>
    #include<fcntl.h>
    #include<stdio.h>
    int main(int argc,char** argv)
    {
            int fdw=open(argv[1],O_WRONLY);
            printf("fdw=%d ",fdw);
            write(fdw,"hello",5);
            return 0;
    }
    //如果打开读端,但是没有打开对应的写端,进程会卡住,等待写端打开

    //管道都是要两端都打开才能正常运行,如果一段打开,一段没有就会阻塞,等待对方打开
    #include<sys/types.h>
    #include<sys/stat.h>
    #include<fcntl.h>
    #include<stdio.h>
    int main(int argc,char** argv)
    {
            int fdr=open(argv[1],O_RDONLY);
            printf("fdr=%d ",fdr);
            char buf[10]="";
            read(fdr,buf,sizeof(buf));
            printf("buf=%s ",buf);
            return 0;
    }
    //打开顺序是先打开写端,在打开写读端



    如果管道写端关闭,读端如果read,会返回0

    改进a.c  //同时打开两个管道 改进b.c
    #include<sys/types.h>
    #include<sys/stat.h>
    #include<fcntl.h>
    #include<unistd.h>
    #include<strings.h>
    #include<stdio.h>
    #include<string.h>
    int main(int argc,char** argv)
    {
            int fdw=open(argv[1],O_WRONLY);
            int fdr=open(argv[2],O_RDONLY);
            printf("fdr=%d fdw=%d ",fdr,fdw);
            char buf[128]="";
            while(1) //如果管道写端关闭,读端如果read,会返回0
            {
                    bzero(buf,sizeof(buf));
                    read(0,buf,sizeof(buf));
                    write(fdw,buf,strlen(buf)-1);  //去掉标准输入最后读到的回车
                    bzero(buf,sizeof(buf));
                    read(fdr,buf,sizeof(buf));
                    printf("b:%s ",buf);                      
            }
            return 0;
    }
    #include<sys/types.h>
    #include<sys/stat.h>
    #include<fcntl.h>
    #include<unistd.h>
    #include<strings.h>
    #include<stdio.h>
    #include<string.h>
    int main(int argc,char** argv)
    {
            int fdr=open(argv[1],O_RDONLY);
            int fdw=open(argv[2],O_WRONLY);
            printf("fdr=%d fdw=%d ",fdr,fdw);
            char buf[128]="";
            while(1)
            {
                    bzero(buf,sizeof(buf));
                    read(fdr,buf,sizeof(buf));
                    printf("a:%s ",buf);
                    bzero(buf,sizeof(buf));
                    read(0,buf,sizeof(buf));
                    write(fdw,buf,strlen(buf)-1);  //去掉标准输入最后读到的回车
            }
            return 0;
    }


    //只能你读一句我读一句,不然会卡住



  • 相关阅读:
    插入排序
    2019何凯文五夜十篇
    文件
    结构体数组表示
    位运算应用
    条件编译 预处理命令
    文件包含
    带参宏定义
    宏定义有无参数宏定义和带参数宏定义两种
    phpcms v9网站搬家更换域名的方法
  • 原文地址:https://www.cnblogs.com/meihao1203/p/8443827.html
Copyright © 2020-2023  润新知