消息队列创建以及使用示例
消息队列是消息的链接表,存放在内核中并由消息队列标示符标识。
1. 创建或打开一个队列
int msgget(key_t key, int flag);
key: 键 由ftok()生成
key_t ftok(const char* path, int id);
flag: IPC_CREAT 或 IPC_EXCL
2. 发送消息
int msgsnd(int msgid, const void* ptr, size_t nbyte, int flag);
msgid: 消息队列标识
ptr: 发送的消息,一般格式为:
struct _msg{
long mtype;
char _msg[512];
. . .
};
nbyte:消息大小,一般为sizeof(struct _msg)-sizeof(long)
flag: 0 默认阻塞方式
IPC_NOWAIT 非阻塞
3. 接收消息
int msgrcv(int msgid, void* ptr, size_t nbyte, long mtype, int flag);
msgQueue.h
#ifndef _MSGQUEUE_H_
#define _MSGQUEUE_H_
#include
#include
#include
#include
#include
using namespace std;
#define KEYPATH "/tmp/count"
#define KEYPROJ 'a'
#define NAMESIZE 16
#define MTYPE 2
typedef struct {
long mtype;
char name[NAMESIZE];
int iChiScore;
int iEngScore;
int iMathScore;
} S_SCORE_ST;
#endif
send.c
#include "msgQueue.h"
int main()
{
int iRet = 0;
key_t key;
int msgid;
S_SCORE_ST score_st;
do {
key = ftok(KEYPATH, KEYPROJ);
if (key < 0) {
iRet = -1;
cout << "ftok() error : " << key << endl;
break;
}
msgid = msgget(key, IPC_CREAT);
if (msgid < 0) {
iRet = -1;
cout << "msgget() error : " << msgid << endl;
break;
}
strcpy(score_st.name, "leex");
score_st.iChiScore = 100;
score_st.iEngScore = 100;
score_st.iMathScore = 100;
score_st.mtype = MTYPE;
iRet = msgsnd(msgid, &score_st, sizeof(score_st)-sizeof(long), 0);
if (iRet < 0) {
cout << "msgsnd() error : " << iRet << endl;
break;
}
} while(false);
return iRet;
}
recv.c
#include "msgQueue.h"
int main()
{
int iRet = 0;
key_t key;
int msgid;
S_SCORE_ST score_st;
do {
key = ftok(KEYPATH, KEYPROJ);
if (key < 0) {
iRet = -1;
cout << "ftok() error : " << key << endl;
break;
}
msgid = msgget(key, IPC_CREAT);
if (msgid < 0) {
iRet = -1;
cout << "msgget() error : " << msgid << endl;
break;
}
while (1) {
iRet = msgrcv(msgid, &score_st, sizeof(score_st)-sizeof(long), MTYPE, 0);
if (iRet < 0) {
cout << "msgrcv() error : " << iRet << endl;
break;
}
cout << "name:\t" << score_st.name << endl;
cout << "chinese score:\t" << score_st.iChiScore << endl;
cout << "english score:\t" << score_st.iEngScore << endl;
cout << "math score:\t" << score_st.iMathScore << endl;
}
} while(false);
return iRet;
}