C++ 中消息队列函数实例详解
1.消息队列结构体的定义
typedef struct{
uid_t uid;
gid_t gid;
udi_t cuid;
gid_t cgid;
mode_t mode;
ulong_t seq;
}ipc_perm;
typedef stuct{
struct ipc_perm msg_perm;
struct msg *msg_first;
struct msg *msg_last;
msglen_t msg_cbytes;
msgqnum_t msg_qnum;
msglen_t msg_qbytes;
pid_t msg_lspid;
pid_t msg_lrpid;
time_tmsg_stime;
time_tmsg_rtime;
time_tmsg_ctime;
}msqid_ds;
typedef struct
{
long mtype;
char mbuf[MSGLEN];
}Message;
2.创建消息队列:
#include#include #include int MsgGet(int key) { int ret; ret=msgget(key,0600|IPC_CREAT); // ret=msgget(key,0600|IPC_CREAT|IPC_EXCL); if(ret<0) perror("creat msgid error"); printf("msgid=%d/n",ret); system("ipcs -q -i ret"); return ret; } int main(int argc,char *agrv[]) { int key; printf("pleasse input msgkey:"); scanf("%d",&key); MsgGet(key); return 0; }
3.向消息队列中发送消息msgsnd
#include "typemsg.h"
int MsgSnd(int msqid,char *buf,int len,int flag)
{
int ret;
ret=msgsnd(msqid,buf,len,flag);
if(ret<0)
perror("msgsnd error");
system("ipcs -q");
return ret;
}
int main()
{
int msqid,len,stype;
Message msgb;
memset(&msgb,0,sizeof(Message));
printf("msgsnd:please input msqid:");
scanf("%d",&msqid);
printf("please input msgtype:");
scanf("%d",&stype);
msgb.mtype=stype;
strcpy(msgb.mbuf,"zhangweia");
MsgSnd(msqid,(char *)&msgb,sizeof(Message),0);
return 0;
}
4.从队列中获取消息 msgrcv
#include "typemsg.h"
int MsgRcv(int msqid,char *buf,int msglen,long type,int flag)
{
int ret;
ret=msgrcv(msqid,buf,msglen,type,flag);
if(ret<0)
perror("msgrcv error");
system("ipcs -q");
return ret;
}
int main()
{
int msqid,len;
long ttype;
Message mbuf;
printf("msgrcv:please input recv msqid:");
scanf("%d",&msqid);
MsgRcv(msqid,(char *)&mbuf,8900,0,IPC_NOWAIT);
printf("recv message=%s/n",mbuf.mbuf);
Put_String((unsigned char *)&mbuf,sizeof(Message));
return 0;
}
6.消息队列的控制msgctl
#include "typemsg.h"
int MsgCtl(int msqid,int cmd,struct msqid_ds *buff)
{
int ret;
ret=msgctl(msqid,cmd,buff);
if(ret<0)
{
perror("msgctl error");
return -1;
}
return 0;
}
int main()
{
int msqid,type;
struct msqid_ds info;
printf("please input msqid /nand type(1:icp_rmid;2:ipc_stat)");
scanf("%d%d",&msqid,&type);
if(type==1)
{
MsgCtl(msqid,IPC_RMID,NULL);
printf("delete queue success:%d/n",msqid);
}else if(type==2)
{
MsgCtl(msqid,IPC_STAT,&info);
printf("get queue stat:%d/n",msqid);
}
return 0;
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!



