msgrcv()函数特性

操作系统提供的消息队列收发函数,接收函数有一个特性,以前一直没理解清楚,今天测试确认了。

函数:

int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);

ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);

参数说明

msqid:消息队列的识别码。
msgp:指向消息缓冲区的指针,此位置用来暂时存储发送和接收的消息,是一个用户可定义的通用结构,形态如下

struct msgbuf {
    long mtype;     /* 消息类型,必须 > 0 */
    char mtext[1];  /* 消息文本 */
};

msgsz:消息的大小。
msgtyp:从消息队列内读取的消息形态。

msgflg:用来指明核心程序在队列没有数据的情况下所应采取的行动。

特性说明:

msgsnd()时,第二个参数(输入参数)msgp是个结构体指针,指向内容有两个字段,mtype表示消息类型,mtext表示参数内容,内容长度一般不能太大,占用的是操作系统的消息队列空间。

msgrcv()时,第二个参数(输入参数)msgp用来接收消息内容,第4个参数用msgtype来指定消息类型,即从同一个msgqid里面可以接收不同类型的消息,这个msgtype官方说明如下:

The argument msgtyp specifies the type of message requested as follows:
       * If msgtyp is 0, then the first message in the queue is read.
       * If msgtyp is greater than 0, then the first message in the queue of type msgtyp  is  read,  unless  MSG_EXCEPT  was
         specified in msgflg, in which case the first message in the queue of type not equal to msgtyp will be read.
       * If  msgtyp is less than 0, then the first message in the queue with the lowest type less than or equal to the abso-
         lute value of msgtyp will be read.

为0时,就是接收队列里的第一个消息,绝对是第一个消息;

>0时,接收队列中第一个类型为msgtype的消息,这里不一定是队列首个消息,可以读取队列里第2、3、....个消息,这个经过测试验证过了。

<0时,接收队列中第一个小于、等于|msgtype|的消息,不一定是第一个消息,如果队首消息大于|msgtype|将不会被取走。

结论:

操作系统提供的消息队列,确保同一个类型的消息是先进先出的,整个队列的消息可能不是先进先出的。

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值