发送程序:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf
{
long mtype; // 消息的标识(整数)
char mtext[100]; // 消息的正文
};
int main()
{
//1.创建KEY值
key_t key = ftok("./", 0);
if(-1 ==key)
{
printf("creat key failed");
return -1;
}
//2.创建消息队列
int msg_id = msgget(key, IPC_CREAT | 0777);
if(-1 == msg_id)
{
printf("creat msg failed\n");
return -1;
}
//3.往消息队列里面发送消息
//需要定义一个结构体变量buf
struct msgbuf buf;
//需要给结构体成员赋值,若从键盘获取就不必赋值
//buf.mtype = 1;
while(1)
{
printf("请输入消息标识\n");
scanf("%ld",&buf.mtype);
//scanf以回车作为输入完成的标志
//键盘输入消息标识后敲的换行没用被获取走,scanf会残留\n
//需要用getchar()清除残留的\n
//否则fgets()无法从键盘正确获取消息
getchar();
memset(buf.mtext,0,100);
//消息从键盘获取
fgets(buf.mtext,100,stdin);//以回车结尾
int msgsnd_ret = msgsnd(msg_id,&buf,sizeof(buf), 0); //默认是阻塞的发送
if(-1 == msgsnd_ret)
{
printf("send msg failed\n");
return -1;
}
if(strcmp(buf.mtext, "bye\n") == 0)
{
break;
}
}
}
接收程序:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf
{
long mtype; // 消息的标识(整数)
char mtext[100]; // 消息的正文
};
int main()
{
//key值
key_t key = ftok("./", 0);
if(-1 ==key)
{
printf("creat key failed");
return -1;
}
//创建消息队列
int msg_id = msgget(key, IPC_CREAT | 0777);
if(-1 == msg_id)
{
printf("creat msg failed\n");
return -1;
}
//接受消息的消息
struct msgbuf buf;
//定义变量赋值消息标识
int a = 0;
while(1)
{
//先输入我要接收的消息的标识
printf("请输入要接收的消息的消息标识\n");
scanf("%d",&a);
memset(buf.mtext,0,100);
ssize_t msgrcv_ret = msgrcv(msg_id, &buf,sizeof(buf), a, 0);
if(-1 == msgrcv_ret)
{
printf("rcv msg failed\n");
}
if(strcmp(buf.mtext,"bye\n")==0)
{
break;
}
printf("MSG:%s\n",buf.mtext);
}
}