1)类型字段可用于标识消息,从而允许多个进程在单个队列上复用消息。
2)类型字段可用作优先级字段。这允许接收者以不同于先进先出的某个顺序读出各个消息。使用管道或FIFO时,数据必须以写入的顺序读出。使用System V消息队列时,消息能够以任意顺序读出,只要跟消息类型关联的值一致就行。
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
#define KEY_MSG 0x101
#define MSGSIZE 64
typedef struct
{
long mtype;
char mtext[MSGSIZE];
}msgbuf;
#define LEN sizeof(msgbuf)-sizeof(long)
void main()
{
int msgid;
msgbuf buf1,buf2;
msgid=msgget(KEY_MSG,IPC_CREAT|0666);
while(1)
{
msgrcv(msgid,&buf1,LEN,1L,0); //接收1的消息,返回类型为1L的第一个消息
printf("Receive client1 message:%s\n",buf1.mtext);
if(buf1.mtext[0]=='x' || buf1.mtext[0]=='X')
{
strcpy(buf1.mtext,"x");
buf1.mtype=3L;
msgsnd(msgid,&buf1,LEN,0);
buf1.mtype=4L;
msgsnd(msgid,&buf1,LEN,0);
break;
}