加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 服务器 > 搭建环境 > Windows > 正文

Linux下的进程间通信:使用管道和消息队列

发布时间:2019-05-14 00:28:20 所属栏目:Windows 来源:Marty Kalin
导读:副标题#e# 学习在 Linux 中进程是如何与其他进程进行同步的。 本篇是 Linux 下进程间通信(IPC)系列的第二篇文章。第一篇文章 聚焦于通过共享文件和共享内存段这样的共享存储来进行 IPC。这篇文件的重点将转向管道,它是连接需要通信的进程之间的通道。管

首先程序创建了一个命名管道用来写入数据:

  1. mkfifo(pipeName, 0666); /* read/write perms for user/group/others */
  2. int fd = open(pipeName, O_CREAT | O_WRONLY);

其中的 pipeName 是备份文件的名字,传递给 mkfifo 作为它的第一个参数。接着命名管道通过我们熟悉的 open 函数调用被打开,而这个函数将会返回一个文件描述符。

  • 在实现层面上,fifoWriter 不会一次性将所有的数据都写入,而是写入一个块,然后休息随机数目的微秒时间,接着再循环往复。总的来说,有 768000 个 4 字节整数值被写入到命名管道中。

  • 在关闭命名管道后,fifoWriter 也将使用 unlink 取消对该文件的连接。

    1. close(fd); /* close pipe: generates end-of-stream marker */
    2. unlink(pipeName); /* unlink from the implementing file */

    一旦连接到管道的每个进程都执行了 unlink 操作后,系统将回收这些备份文件。在这个例子中,只有两个这样的进程 fifoWriterfifoReader,它们都做了 unlink 操作。

  • 这个两个程序应该在不同终端的相同工作目录中执行。但是 fifoWriter 应该在 fifoReader 之前被启动,因为需要 fifoWriter 去创建管道。然后 fifoReader 才能够获取到刚被创建的命名管道。

    示例 3. fifoReader 程序

    1. #include <stdio.h>
    2. #include <stdlib.h>
    3. #include <string.h>
    4. #include <fcntl.h>
    5. #include <unistd.h>
    6.  
    7.  
    8. unsigned is_prime(unsigned n) { /* not pretty, but gets the job done efficiently */
    9. if (n <= 3) return n > 1;
    10. if (0 == (n % 2) || 0 == (n % 3)) return 0;
    11.  
    12. unsigned i;
    13. for (i = 5; (i * i) <= n; i += 6)
    14. if (0 == (n % i) || 0 == (n % (i + 2))) return 0;
    15.  
    16. return 1; /* found a prime! */
    17. }
    18.  
    19. int main() {
    20. const char* file = "./fifoChannel";
    21. int fd = open(file, O_RDONLY);
    22. if (fd < 0) return -1; /* no point in continuing */
    23. unsigned count = 0, total = 0, primes_count = 0;
    24.  
    25. while (1) {
    26. int next;
    27. int i;
    28. ssize_t count = read(fd, &next, sizeof(int));
    29.  
    30. if (0 == count) break; /* end of stream */
    31. else if (count == sizeof(int)) { /* read a 4-byte int value */
    32. total++;
    33. if (is_prime(next)) primes_count++;
    34. }
    35. }
    36.  
    37. close(fd); /* close pipe from read end */
    38. unlink(file); /* unlink from the underlying file */
    39. [printf][10]("Received ints: %u, primes: %un", total, primes_count);
    40.  
    41. return 0;
    42. }

    上面的 fifoReader 的内容可以总结为如下:

    • (编辑:PHP编程网 - 黄冈站长网)

      【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读