#include<sys/types.h>
#include<sys/msg.h>
#include<unistd.h>
struct msg_buf
{
int mtype; //消息类型
char data[255]; //消息文本
};
int main()
{
key_t key;
int msgid;
int ret;
struct msg_buf msgbuf;
key=ftok("/tmp/2",'a'); //取得文件对应的键值
printf("key=[%x]\n",key);
msgid=msgget(key,IPC_CREAT|0666); //打开键值对应的消息队列,若没有则创建此消息对列,并返回其标识符
if(msgid==-1)
{
printf("create error\n");
return -1;
}
msgbuf.mtype=getpid(); //将进程ID作为消息类型
strcpy(msgbuf.data,"test haha"); //填充消息文本
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("recv message err\n");
return -1;
}
printf("recv msg=[%s]\n",msgbuf.data);
}