消息队列和共享内存相似,可以用于进程间通信。
1.c
#include "../common.h"
#define MSG_FILE "./1.c"
struct my_msg
{
long int mtype; //必须为长整型
char mbuf[80];
};
int main()
{
int msqid = -1;
key_t key = -1;
struct my_msg smsg,rmsg;
/* 获取唯一key */
if((key = ftok(MSG_FILE,'z'))<0)
{
perror("ftok");
return -1;
}
printf("key: %d\n",key);
/* 创建消息队列 */
if ((msqid = msgget(key, IPC_CREAT|0777)) == -1)
{
perror("msgget");
return -1;
}
strcpy(smsg.mbuf,"START");
smsg.mtype = 999; // 发送的消息类型
msgsnd(msqid, &smsg, 80, 0);
msgrcv(msqid, &rmsg, 80, 888, 0);// 返回类型为888的第一个消息
printf("Server: receive msg.mtext is: %s.\n", rmsg.mbuf);
printf("Server: receive msg.mtype is: %ld.\n", rmsg.mtype);
if (msgctl(msqid, IPC_RMID, 0) == -1)
{
printf("msgctl(IPC_RMID) failed\n");
}
}
2.c
#include "../common.h"
#define MSG_FILE "./1.c"
struct my_msg
{
long int mtype; //必须为长整型
char mbuf[80];
};
int main()
{
int msqid = -1;
key_t key = -1;
struct my_msg smsg,rmsg;
/* 获取唯一key */
if((key = ftok(MSG_FILE,'z'))<0)
{
perror("ftok");
return -1;
}
printf("key: %d\n",key);
/* 创建消息队列 */
if ((msqid = msgget(key, IPC_CREAT|0777)) == -1)
{
perror("msgget");
return -1;
}
msgrcv(msqid, &rmsg, 80, 999, 0);// 返回类型为999的第一个消息
printf("Server: receive msg.mtext is: %s.\n", rmsg.mbuf);
printf("Server: receive msg.mtype is: %ld.\n", rmsg.mtype);
sprintf(smsg.mbuf,"end");
smsg.mtype = 888; // 发送到队列的消息类型
msgsnd(msqid, &smsg, 80, 0);
}
结果:
bekl@ubuntu:~/TEST/消息队列$ ./1
key: 2046887386
Server: receive msg.mtext is: end.
Server: receive msg.mtype is: 888.
bekl@ubuntu:~/TEST/消息队列$ ./2
key: 2046887386
Server: receive msg.mtext is: START.
Server: receive msg.mtype is: 999.