消息队列
消息队列与命名管道很相似,它提供了一种在两个不相关之间传递数据的相当简单且有效的方法。与命名管道相比,消息队列的优势在于,它独立于发送和接受进程而存在,这消除了在同步命名管道的打开和关闭时可能产生的一些困难。(某个进程往一个消息队列中写入消息之前,不需要另外某个进程在该队列上等待消息的达到)
接口函数
#include<sys/msg.h>
/*
控制函数,一般用于删除消息队列
cmd:IPC_RMID 删除消息队列
*/
int msgctl(int msqid,int cmd,struct msqid_ds *buf);
/*
创建和访问一个消息队列,成功时返回一个正整数,失败返回-1;
msgflag:由IPC_CREAT定义的一个特殊为必须和权限标志按位或才能创建一个新的消息队列
*/
int msgget(key_t key,int msgflg);
/*
从一个消息队列中获取消息,成功时返回放到接收缓冲区中的字节数,消息被复制到由msg_ptr指向的用户分配的缓冲区中,然后删除消息队列中的对应消息,失败返回-1
*/
int msgrcv(int msqid,void *msg_ptr,size_t msg_sz,long int msgtype,int msgflg);
/*
把消息添加到消息队列中,成功时返回0,失败返回-1.如果调用成功,消息数据的一份副本将被放到消息队列中。
*/
int msgsnd(int msqid,const void *msg_ptr,size_t msg_sz,int msgflg)
示例
a程序:写操作
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<sys/msg.h>
struct mess
{
long type;
char buff[32];
};
int main()
{
int msgid=msgget((key_t)1234,IPC_CREAT|0600);//创建消息队列
assert(msgid!=-1);
struct mess dt;
dt.type=1;
strcpy(dt.buff,"hello");
msgsnd(msgid,(void*)&dt,32,0);//添加消息到消息队列中
exit(0);
}
b程序:读操作
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<sys/msg.h>
struct mess
{
long type;
char buff[32];
};
int main()
{
int msgid=msgget((key_t)1234,IPC_CREAT|0600);
assert(msgid!=-1);
struct mess dt;
msgrcv(msgid,(void *)&dt,32,1,0);
printf("dt.buff=%s\n",dt.buff);
if( msgctl(msgid,IPC_RMID,0)==-1)
{
fprintf(stderr,"msgctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
exit(0);
}
以上,我们允许两个程序都可以创建消息队列,但只有接收者在接受完最后一个消息之后可以删除它(消息队列)。