#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#define XM_XH 1L
#define XG_XH 2L
struct msgbuf
{
long mtype; // 消息的标识
char mtext[1024]; // 消息的正文
};
int main(int argc, char const *argv[])
{
//得到键值
key_t key = ftok("./", 3);
if (key == -1)
{
perror("ftok");
return -1;
}
//获取消息队列的ID
int msgid = msgget(key, IPC_CREAT | 0777);
if (msgid == -1)
{
perror("msgget");
return -1;
}
//获取消息队列的ID
int msgid2 = msgget(key, IPC_CREAT | 0777);
if (msgid2 == -1)
{
perror("msgget");
return -1;
}
struct msgbuf buf;
//接收小明消息,消息队列里面,如果没有数据拿,会阻塞的
msgrcv(msgid, &buf, sizeof(buf.mtext), XM_XH, 0);
printf("小明:%s\n", buf.mtext);
// printf("%s\n", "yes,i like you honey.");
struct msgbuf buf1;
buf1.mtype = XM_XH;
strcpy(buf1.mtext, "yes,i like you honey.");
//发送消息
int ret1 = msgsnd(msgid, &buf1, strlen(buf1.mtext)+1, 0);
if (ret1 == -1)
{
printf("发送失败\n");
}
//接收小刚消息,消息队列里面,如果没有数据拿,会阻塞的
msgrcv(msgid2, &buf, sizeof(buf.mtext), XG_XH, 0);
printf("小刚:%s\n", buf.mtext);
// printf("%s\n", "sorry,i like xiaoming,you are good boy.");
struct msgbuf buf2;
buf2.mtype = XG_XH;
strcpy(buf2.mtext, "sorry,i like xiaoming,you are good boy.");
//发送消息
int ret2 = msgsnd(msgid, &buf2, strlen(buf2.mtext)+1, 0);
if (ret2 == -1)
{
printf("发送失败\n");
}
//删除消息队列(谨慎)
// msgctl(msgid, IPC_RMID, NULL);
return 0;
}