创建/打开消息队列 msgget
发送数据 msgsnd
从消息队列取消息 msgrcv
删除消息队列 msgctl
例如A进程代码
#include
#include
#include
#include
#include
#include
struct msgt
{
long msgtype;
char msgtext[1024];
};
void main()
{
int msqid;
int msg_type;
char str[256];
struct msgt msgs;
//创建消息队列
msqid = msgget(1025, IPC_CREAT);
//循环
while(1)
{
printf("please input message type, 0 for quit!\n");
//获取消息类型
scanf("%d", &msg_type);
//如果用户输入的消息为0,则退出
if(msg_type == 0)
break;
printf("please input message data!\n");
//获取消息数据
scanf("%s", str);
msgs.msgtype = msg_type;
strcpy(msgs.msgtext, str);
//发送消息
msgsnd(msqid, &msgs, sizeof(struct msgt), 0);
}
//删除消息队列
msgctl(msqid, IPC_RMID, 0);
}
B进程代码
#include
#include
#include
#include
#include
#include
int msqid;
struct msgt
{
long msgtype;
char msgtext[1024];
};
void myprocess()
{
struct msgt ms;
int x;
x = msgrcv(msqid, &ms, sizeof(struct msgt), 0, 0);
printf("the receive text: %s %d\n", ms.msgtext, x);
}
void main()
{
int i;
int cpid;
//打开消息队列
msqid = msgget(1025, IPC_EXCL);
printf("the msqid is %d\n", msqid);
myprocess();
}