三、四个列子
例1:接收消息
int read_message(int qid, long type, struct mymsgbuf *qbuf)
{
int result, length;
length = sizeof(struct mymsgbuf)-sizeof(long);
if((result = msgrcv(qid, qbuf, length, type, 0)) == -1)
{
return -1;
}
return result;
}
例2:消息队列之简单收发测试
#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
struct msg_buf
{
int mtype;//消息类型
char data[255];//数据
};
int main(int argc, char *argv[])
{
key_t key;
int msgid;
int ret;
struct msg_buf msgbuf;
//获取key值
key = ftok(".", 'a');
printf("key = [%x]\n", key);
//创建消息队列
msgid = msgget(key, IPC_CREAT|0666);/*通过文件对应*/
if(msgid == -1)
{
printf("creat error\n");
return -1;
}
//以当前进程类型,非阻塞方式发送"test data"到消息队列
msgbuf.mtype = getpid();
strcpy(msgbuf.data, "test data");
ret = msgsnd(msgid, &msgbuf, sizeof(msgbuf.data), IPC_NOWAIT);
if(ret == -1)
{
printf("send message err\n");
return -1;
}
//以非阻塞方式接收数据
memset(&msgbuf, 0, sizeof(msgbuf));
ret = msgrcv(msgid, &msgbuf, sizeof(msgbuf.data), getpid(), IPC_NOWAIT);
if(ret == -1)
{
printf("receive message err\n");
return -1;
}
printf("receive msg = [%s]\n", msgbuf.data);
return 0;
}
