[C.C++] C++管道

803 0
Honkers 2025-8-27 01:36:08 来自手机 | 显示全部楼层 |阅读模式

        管道是一种单向通信的方式,一般用于进程间通信,在零拷贝时也会用到管道。管道本质上是一个文件,一个进程读,一个进程写。但是管道本身不占用磁盘或者其他外部存储的空间。在Linux上它占用内存空间。所以管道就是一个操作方式为文件的内存缓冲区。也正是因为管道是内存中的,所以它比使用文件作通信更快。

1.命名管道:

        命名管道需要包含头文件:#include   #include

        命名管道相当于创建了一个有命的文件,那么任何进程只要知道它的文件名就可以使用该管道,因此它不受亲缘进程的影响。命名管道创建和使用方式与文件差距不大,它使用mkfifo创建并使用open,write和read来打开,写和读。但是一个进程对命名管道只可以读和写选一个,不可以即读又写。例:

  1. #include <sys/types.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <cstring>
  7. #include <cstdio>
  8. #include <iostream>
  9. const char buf[] = "hello";
  10. const int32_t bufSize = sizeof(buf);
  11. const char str[] = "/root/namePipe";
  12. int main()
  13. {
  14. //创建命名管道
  15. int32_t ret = mkfifo(str, S_IFIFO | 0666);
  16. if (ret == -1)
  17. {
  18. std::cout << "Make fifo error\n";
  19. return -1;
  20. }
  21. pid_t pid;
  22. pid = fork();
  23. if (pid > 0) {
  24. int32_t fd = open(str, O_WRONLY);
  25. if (write(fd, buf, bufSize) < 0) {
  26. std::cout << "write error\n";
  27. }
  28. close(fd);
  29. return 0;
  30. }
  31. sleep(1);
  32. char readBuf[bufSize];
  33. int32_t fd = open(str, O_RDONLY);
  34. if (read(fd, readBuf, bufSize) < 0) {
  35. std::cout << "read error\n";
  36. }
  37. else {
  38. std::cout << buf << '\n';
  39. }
  40. close(fd);
  41. return 0;
  42. }
复制代码

         删除命名管道可以用linux的unlink命令

  1. unlink 管道名
复制代码

2.匿名管道:

        匿名管道使用pipe创建,需要包含头文件:#include

        pipe会初始化一个int[2],其中一个只读,另一个只写。由于它没有文件名,只有int变量存储的文件描述符,因此只有有血缘关系的进程才能使用它通信。匿名管道用法如下:

  1. #include <sys/types.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4. #include <fcntl.h>
  5. #include <cstring>
  6. #include <cstdio>
  7. #include <iostream>
  8. int main()
  9. {
  10. int32_t pipeFd[2];
  11. if (pipe(pipeFd) == -1) {
  12. perror("Pipe failed:");
  13. return 0;
  14. }
  15. pid_t pid;
  16. pid = fork();
  17. if (pid > 0) {
  18. close(pipeFd[0]); //父进程只写,所以关闭读描述符
  19. char buf[] = "hello";
  20. if (write(pipeFd[1], buf, sizeof(buf)) < 0) {
  21. perror("Write error:");
  22. }
  23. close(pipeFd[1]);
  24. wait(nullptr); //防僵尸进程
  25. return 0;
  26. }
  27. close(pipeFd[1]); //子进程只读,关闭写描述符
  28. char buf[32];
  29. memset(buf, 0, 32);
  30. if (read(pipeFd[0], buf, 32) < 0) {
  31. perror("Read error:");
  32. }
  33. else {
  34. std::cout << buf << '\n';
  35. }
  36. close(pipeFd[0]);
  37. return 0;
  38. }
复制代码

        需要注意的是如果所有管道的读描述符被关闭,那么写将阻塞。如果所有的写描述符已关闭,那么读将无法读到返回0。

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行