1.server.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
// 用于创建一个唯一的key
// 消息结构
struct msg_form {
long mtype;
char mtext[256];
};
int main()
{
int msqid;
key_t key;
struct msg_form msg;
// 获取key值
if((key = ftok(".",1)) < 0)
{
perror("ftok error");
exit(1);
}
// 打印key值
printf("Message Queue - Server key is: %d.\n", key);
// 创建消息队列
if ((msqid = msgget(key, IPC_CREAT|0777)) == -1)
{
perror("msgget error");
exit(1);
}
// 打印消息队列ID及进程ID
printf("My msqid is: %d.\n", msqid);
// 循环读取消息
msgrcv(msqid, &msg, sizeof(msg.mtext), 880, 0);// 返回类型为888的第一个消息
printf(“Server: receive msg.mtext is: %s.\n”, msg.mtext);
printf(“Server: receive msg.mtype is: %ld.\n”, msg.mtype);
struct msg_form sendBuf = {989,"thank you for reach"};
msgsnd(msqid, &sendBuf,strlen(sendBuf.mtext), 0);
msgctl(msqid,IPC_RMID,NULL);
return 0;
}
2.client.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <string.h>
// 用于创建一个唯一的key
// 消息结构
struct msg_form {
long mtype;
char mtext[256];
};
int main()
{
int msqid;
key_t key;
struct msg_form msg;
// 获取key值
if ((key = ftok(".", 1)) < 0)
{
perror("ftok error");
exit(1);
}
// 打印key值
printf("Message Queue - Client key is: %d.\n", key);
// 打开消息队列
if ((msqid = msgget(key, IPC_CREAT|0777)) == -1)
{
perror("msgget error");
exit(1);
}
// 打印消息队列ID及进程ID
printf("My msqid is: %d.\n", msqid);
// 添加消息,类型为888
struct msg_form sendBuf = {880,“this is message from quen”};
msgsnd(msqid,&sendBuf,strlen(sendBuf.mtext),0);
// 读取类型为777的消息
msgrcv(msqid, &msg, sizeof(msg.mtext), 989, 0);
printf("Client: receive msg.mtext is: %s.\n", msg.mtext);
printf("Client: receive msg.mtype is: %ld.\n", msg.mtype);
msgctl(msqid,IPC_RMID,NULL);
return 0;
}