Linux进程间的五种通信方式介绍 2

电子说

1.2w人已加入

描述

在两个终端里用 gcc 分别编译运行上面两个文件,可以看到输出结果如下:

[xq@localhost]$ ./write_fifoI am 7872 processSend message: Process 7872's time is Mon Jan 16 18:00:23 2023Send message: Process 7872's time is Mon Jan 16 18:00:24 2023Send message: Process 7872's time is Mon Jan 16 18:00:25 2023Send message: Process 7872's time is Mon Jan 16 18:00:26 2023Send message: Process 7872's time is Mon Jan 16 18:00:27 2023Send message: Process 7872's time is Mon Jan 16 18:00:28 2023Send message: Process 7872's time is Mon Jan 16 18:00:29 2023Send message: Process 7872's time is Mon Jan 16 18:00:30 2023Send message: Process 7872's time is Mon Jan 16 18:00:31 2023Send message: Process 7872's time is Mon Jan 16 18:00:32 2023
[xq@localhost]$ ./write_fifoI am 7872 processSend message: Process 7872's time is Mon Jan 16 18:00:23 2023Send message: Process 7872's time is Mon Jan 16 18:00:24 2023Send message: Process 7872's time is Mon Jan 16 18:00:25 2023Send message: Process 7872's time is Mon Jan 16 18:00:26 2023Send message: Process 7872's time is Mon Jan 16 18:00:27 2023Send message: Process 7872's time is Mon Jan 16 18:00:28 2023Send message: Process 7872's time is Mon Jan 16 18:00:29 2023Send message: Process 7872's time is Mon Jan 16 18:00:30 2023Send message: Process 7872's time is Mon Jan 16 18:00:31 2023Send message: Process 7872's time is Mon Jan 16 18:00:32 2023

上面的例子可以扩展成 客户端进程—服务端进程通信的实例,write_fifo的作用类似于客户端,可以打开多个客户端向一个服务器发送请求信息,read_fifo类似于服务器,它适时监控着FIFO的读端,当有数据时,读出并进行处理,但是有一个关键的问题是,每一个客户端必须预先知道服务器提供的FIFO接口,下图显示了这样的操作:

IPC

三、消息队列

消息队列,是消息的链接表,存放在内核中。一个消息队列由一个标识符(即队列ID)来标识。

1、特点

  1. 消息队列是面向记录的,其中的消息具有特定的格式以及特定的优先级。
  2. 消息队列独立于发送与接收进程。进程终止时,消息队列及其内容并不会被删除。
  3. 消息队列可以实现消息的随机查询,消息不一定要以先进先出的次序读取,也可以按消息的类型读取。

2、原型

#include// 创建或打开消息队列:成功返回队列ID,失败返回-1intmsgget(key_t key, int flag);// 添加消息:成功返回0,失败返回-1intmsgsnd(int msqid, constvoid ptr, size_t size, int flag);// 读取消息:成功返回消息数据的长度,失败返回-1intmsgrcv(int msqid, void* ptr, size_t size, long type, int flag);// 控制消息队列:成功返回0, 失败返回-1intmsgctl(int msqid, int cmd, struct msqid_ds * buf);

在以下两种情况下,msgget将创建一个新的消息队列:

  • 如果没有与键值key相对应的消息队列,并且flag中包含了IPC_CREAT标志位。
  • key参数为IPC_PRIVATE。

函数msgrcv在读取消息队列时,type参数有下面几种情况:

  • type == 0,返回队列中的第一个消息;
  • type > 0,返回队列中消息类型为 type 的第一个消息;
  • type < 0,返回队列中消息类型值小于或等于 type 绝对值的消息,如果有多个,则取类型值最小的消息。

可以看出,type值非 0 时用于以非先进先出次序读消息。也可以把 type 看做优先级的权值。(其他的参数解释,请自行Google之)

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分