当前位置:   article > 正文

linux——FIFO命名管道(调用open打开管道)_ubuntu如何使用open打开命名管道

ubuntu如何使用open打开命名管道

当open一个FIFO时,是否设置非阻塞标志(O_NONBLOCK)的区别:

        若没有执行O_NONBLOCK(默认),只读open要阻塞到某个其他进程为写而打开此FIFO。类似的,只写open要阻塞到其他进程为读而打开它。

        若指定了O_NONBLOCK,则只读open立即返回。而只写open将出错返回-1,如果没有进程已经为读而打开该FIFO,其errno置ENXIO。

read.c文件:

  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <stdio.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. // int mkfifo(const char *pathname, mode_t mode);
  7. int main()
  8. {
  9. int nread=0;
  10. char buf[30]={0};
  11. if((mkfifo("./file",0600)==-1)&&errno!=EEXIST){
  12. printf("mkfifo fail\n");
  13. perror("why");
  14. }
  15. int fd=open("./file",O_RDONLY);
  16. printf("open success\n");
  17. while(1){
  18. nread=read(fd,buf,30);
  19. printf("read%dbyte from fifo,context:%s\n",nread,buf);
  20. }
  21. close(fd);
  22. return 0;
  23. }

write.c文件:

  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <stdio.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <string.h>
  7. // int mkfifo(const char *pathname, mode_t mode);
  8. int main()
  9. {
  10. int cnt=0;
  11. char *str="message from fifo";
  12. int fd=open("./file",O_WRONLY);
  13. printf("write open success\n");
  14. while(1){
  15. write(fd,str,strlen(str));
  16. sleep(1);
  17. if(cnt==5){
  18. break;
  19. }
  20. }
  21. close(fd);
  22. return 0;
  23. }

gcc read.c -o read:生成可执行read文件

gcc write.c -o write:生成可执行write文件

./read:运行read

Alt+ctrl+t:重新开个窗口,进入当前read文件夹

./write:运行write

可以看到,write每隔1s往file文件中写入一次数据,read从file中取出数据并打印出来

如果要open不堵塞,则添加O_NONBLOCK

int fd=open("./file",O_RDONLY|O_NONBLOCK);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/837603
推荐阅读
相关标签
  

闽ICP备14008679号