使用消息缓冲队列实现client进程与server进程之间的通信,给出代码
时间: 2024-05-24 22:14:36 浏览: 16
好的,以下是使用消息队列实现client进程与server进程之间通信的示例代码:
// server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_MSG_SIZE 1024
struct msgbuf {
long mtype;
char mtext[MAX_MSG_SIZE];
};
int main() {
// 创建一个key
key_t key = ftok(".", 's');
// 创建一个消息队列
int msgid = msgget(key, IPC_CREAT | S_IRWXU | S_IRWXG | S_IRWXO);
// 接收客户端发送的消息
while (1) {
struct msgbuf buf;
memset(&buf, 0, sizeof(struct msgbuf));
msgrcv(msgid, &buf, MAX_MSG_SIZE, 0, 0);
printf("Server received message: %s\n", buf.mtext);
// 将接收到的消息转为大写字母
int i;
for (i = 0; i < strlen(buf.mtext); i++) {
buf.mtext[i] = toupper(buf.mtext[i]);
}
// 向客户端发送转换后的消息
buf.mtype = 1;
msgsnd(msgid, &buf, strlen(buf.mtext) + 1, 0);
}
// 删除消息队列
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
// client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_MSG_SIZE 1024
struct msgbuf {
long mtype;
char mtext[MAX_MSG_SIZE];
};
int main() {
// 创建一个key
key_t key = ftok(".", 's');
// 获取消息队列id
int msgid = msgget(key, IPC_CREAT | S_IRWXU | S_IRWXG | S_IRWXO);
// 发送消息给server进程
struct msgbuf buf;
buf.mtype = 1;
printf("Please enter a message: ");
fgets(buf.mtext, MAX_MSG_SIZE, stdin);
buf.mtext[strlen(buf.mtext) - 1] = '\0';
msgsnd(msgid, &buf, strlen(buf.mtext) + 1, 0);
// 接收server进程转换后的消息
memset(buf.mtext, 0, MAX_MSG_SIZE);
msgrcv(msgid, &buf, MAX_MSG_SIZE, 1, 0);
printf("Client received message: %s\n", buf.mtext);
// 删除消息队列
msgctl(msgid, IPC_RMID, NULL);
return 0;
}