消息队列:
1.一种从一个进程向另外一个进程发送数据块的方法;
2.每个数据块都被认为是有一个类型,接受者进程接收的数据块可以有不同的类型值;
3.消息队列的读取不一定是先入先出;
4.消息队列的生命周期是随内核的;
5.每个消息的最大长队是由上限的,系统上消息队列的总数也有一个上限。
该函数返回与路径pathname相对应的一个键值key
消息结构定义:
struct msgbuf
{
long
mtype;//消息类型
char mtext[1];//消息数据的首地址
}
如果调用成功,消息数据的一分副本将被放到消息队列中,并返回0,失败时返回-1.
int msgrcv(int msgid, void *msg_ptr, size_t msg_st, long int msgtype, int msgflg);
int msgctl(int msgid, int command, struct msgid_ds *buf);
#include <stdio.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#define PATH "/zyy/nanjing/1.29/msg"
struct msg_buf
{
int mtype;
char mtext[10];
};
void msg_stat(int msgid,struct msqid_ds);
int main()
{
int gflag,sflag,rflag;
key_t key;
int msgid;
int reval;
struct msg_buf msg_sbuf,msg_rbuf;
struct msqid_ds msg_ginfo,msg_sinfo;
key = ftok(PATH,'a');
gflag = IPC_CREAT | IPC_EXCL;
msgid = msgget(key,gflag | 00666);
if(msgid == -1)
{
printf("msg create error\n");
exit(1);
}
//创建一个消息队列后输出其默认属性
msg_stat(msgid,msg_ginfo);
sflag = IPC_NOWAIT;
msg_sbuf.mtype = 10;
strcpy(msg_sbuf.mtext,"abc");
reval = msgsnd(msgid,&msg_sbuf,sizeof(msg_sbuf.mtext),sflag);
if(-1 == reval)
{
printf("message send error\n");
exit(1);
}
//发送一个消息后输出消息队列属性
msg_stat(msgid,msg_ginfo);
rflag = IPC_NOWAIT | MSG_NOERROR;
reval = msgrcv(msgid,&msg_rbuf,4,10,rflag);
if(-1 == reval)
{
printf("message receive error\n");
exit(1);
}
else
{
printf("read from msg queue %d bytes\n",reval);
}
//从消息队列读出消息后,输出消息队列属性
msg_stat(msgid,msg_ginfo);
msg_sinfo.msg_perm.uid = 8;
msg_sinfo.msg_perm.gid = 8;
msg_sinfo.msg_qbytes = 16388;
//此处超级用户可以更改消息队列的默认值msg_qbytes
//注意这里设置的值大于默认值
reval = msgctl(msgid,IPC_SET,&msg_sinfo);
if(-1 == reval)
{
printf("msg set info error\n");
return;
}
msg_stat(msgid,msg_ginfo);
reval = msgctl(msgid,IPC_RMID,NULL);//删除消息队列
if(reval == -1)
{
printf("unlink msg queue error\n");
return;
}
}
void msg_stat(int msgid,struct msqid_ds msg_info)
{
int reval;
sleep(1);
reval = msgctl(msgid,IPC_STAT,&msg_info);
if(reval == -1)
{
printf("get msg info error\n");
return;
}
printf("\n");
printf("current number of bytes on queue is %d\n",msg_info.msg_cbytes);
printf("number of message in queue is %d\n",msg_info.msg_qnum);
printf("max number of bytes in queue is %d\n",msg_info.msg_qbytes);
//每个消息队列的容量(字节数)都有限制MSGMNB,值的大小因系统而异。在创建新的消息队列时,msg_qbytes的默认值是MSGMNB
printf("pid of last msgsnd is %d\n",msg_info.msg_lspid);
printf("pid of last msgrcv is %d\n",msg_info.msg_lrpid);
printf("last msgsnd time is %s",ctime(&(msg_info.msg_stime)));
printf("last msgrcv time is %s",ctime(&(msg_info.msg_rtime)));
printf("last change time is %s",ctime(&(msg_info.msg_ctime)));
printf("mag uid is %d\n",mag_info.msg_perm.uid);
printf("msg gid is %d\n",msg_info.msg_perm.gid);
}