简介

有名管道可以在任意两个进程之间通信,命名管道通常被称为FIFO,创建有名 管道的进程可以给管道取名字以及路径,该路径名是以特殊的⽂件存在放在⽂ 件系统中,因此两个进程可以通过访问该路径来建⽴联系,进⾏进程间的数据 交换,有名管道和⽆名管道都遵循先进先出的原则。 访问命名管道⽂件与访问⽂件系统中的其他⽂件相似,都是需要先打开⽂件, 然后对⽂件进⾏读写数据。
有名管道是⼀个特殊的⽂件,它和普通的⽂件⼀样具有磁盘存放路径,⽂件权 限和其他属性,但是两者⼜有区别,有名管道并不会在磁盘中存放真正的信 息,信息存放在内存中。通讯的两个进程结束后,信息会⾃动消失,但管道⽂件路径依然存在。

有名管道的创建:

1、可以通过命令⾏创建: mkfifo filename
2、通过系统函数调⽤创建:

例子

例:mkfifo的使用

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. int main()
  7. {
  8. char buff[100]={0};
  9. if(access("hello",F_OK)!=0)
  10. {
  11. int pipe_fd=mkfifo("hello",0777);
  12. if(pipe_fd==-1)
  13. {
  14. printf("create faild");
  15. return -1;
  16. }
  17. }
  18. int fd=open("hello",O_RDWR);
  19. write(fd,"hello word!",20);
  20. if(read(fd,buff,20)!=-1)
  21. printf("receive data=%s\n",buff);
  22. close(fd);
  23. return 0;
  24. }

fork()什么时候创建失败
1.内存满的时候
2.内存不够用
例:父子进程之间用有名管道进行通讯

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <sys/wait.h>
  6. #include <stdlib.h>
  7. #include <fcntl.h>
  8. int main()
  9. {
  10. char buff[100]={0};
  11. if(access("hello1",F_OK)!=0)
  12. {
  13. int pipe_fd=mkfifo("hello1",0777);
  14. if(pipe_fd==-1)
  15. {
  16. printf("create faild");
  17. return -1;
  18. }
  19. }
  20. pid_t pid=fork();
  21. if(pid==-1)
  22. {
  23. return -1;
  24. }
  25. if(pid>0)
  26. {
  27. int fd=open("hello1",O_WRONLY);
  28. write(fd,"hello",20);
  29. close(fd);
  30. wait(NULL);
  31. }
  32. else
  33. {
  34. int fd=open("hello1",O_RDONLY);
  35. read(fd,buff,20);
  36. close(fd);
  37. printf("subprocess data:%s\n",buff);
  38. exit(0);
  39. }
  40. printf("end\n");
  41. return 0;
  42. }