发送进程
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<errno.h>
typedef struct msgbuf
{
long mtype;
char mtext[1024];
}msgq_t;
const key_t g_msg_key = 1234;
int main()
{
int ret;
int msg_id;
long int msgtype = 1;
msgq_t data;
//创建消息队列
msg_id = msgget(g_msg_key, IPC_PRIVATE|IPC_CREAT);
if(msg_id == -1)
{
printf("msgget failed:%d\n",errno);
exit(0);
}
data.mtype = msgtype;
//向消息队列中写消息
while(1)
{
memset(data.mtext,0x00,sizeof(data.mtext));
scanf("%s",data.mtext);
ret = msgsnd(msg_id,&data,1024,0);
if(ret == -1)
{
printf("msgsnd failed:%d\n",errno);
}
if(strcmp(data.mtext, "exit") == 0)
{
break;
}
}
//删除消息队列
ret = msgctl(msg_id,IPC_RMID,0);
if(ret == -1)
{
printf("msgctl failed:%d",errno);
}
return 0;
}
接收进程
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<errno.h>
typedef struct msgbuf
{
long mtype;
char mtext[1024];
}msgq_t;
const key_t g_msg_key = 1234;
int main()
{
int ret;
int msg_id;
long int msgtype = -5;
msgq_t data;
//创建消息队列
msg_id = msgget(g_msg_key, IPC_PRIVATE|IPC_CREAT);
if(msg_id == -1)
{
printf("msgget failed:%d\n",errno);
exit(0);
}
while(1)
{
memset(data.mtext,0x00,sizeof(data.mtext));
//从消息队列中获取消息
ret = msgrcv(msg_id,&data,1024,msgtype,0);
if(ret == -1)
{
printf("msgrcv failed:%d\n",errno);
}
else
{
if(strcmp(data.mtext,"exit") == 0)
{
break;
}
else
{
printf("msgrcv:%s\n",data.mtext);
}
}
}
//删除消息队列
ret = msgctl(msg_id,IPC_RMID,0);
if(ret == -1)
{
printf("msgctl failed:%d\n",errno);
}
return 0;
}
查看消息队列