测试代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#define MSGKEY 75
struct msgform {
long mtype;
char mtext[300];
} msg;
int msgqid;
// 客户端消息类型
#define MSG_TYPE_CLIENT_REQ 1
// 服务端消息类型
#define MSG_TYPE_SERVER_RESP 2
void CLIENT() {
int result;
msg.mtype = MSG_TYPE_CLIENT_REQ;
msgqid = msgget(MSGKEY, 0777);
if(msgqid == -1) {
perror("client msgget");
exit(1);
}
for (int i = 0; i < 10; i++) {
sprintf(msg.mtext, "(client) message %d", i+1);
printf("(client) sending: %s\n", msg.mtext);
result = msgsnd(msgqid, &msg, strlen(msg.mtext)+1, 0);
if(result == -1) {
perror("client msgsnd");
exit(1);
}
// 等待并处理服务端响应
msg.mtype = MSG_TYPE_SERVER_RESP;
result = msgrcv(msgqid, &msg, sizeof(msg.mtext), MSG_TYPE_SERVER_RESP, 0);
if(result == -1) {
perror("client msgrcv");
exit(1);
}
printf("(client) received: %s\n", msg.mtext);
}
exit(0);
}
void SERVER() {
int getsize;
msgqid = msgget(MSGKEY, 0777);
if(msgqid == -1) {
perror("server msgget");
exit(1);
}
for (int i = 0; i < 10; i++) {
// 等待客户端请求
msg.mtype = MSG_TYPE_CLIENT_REQ;
getsize = msgrcv(msgqid, &msg, sizeof(msg.mtext), MSG_TYPE_CLIENT_REQ, 0);
if(getsize == -1) {
perror("server msgrcv");
exit(1);
}
printf("(Server) received: %s\n", msg.mtext);
// 构造并发送响应
sprintf(msg.mtext, "(server) response to message %d", i+1);
msg.mtype = MSG_TYPE_SERVER_RESP;
if(msgsnd(msgqid, &msg, strlen(msg.mtext)+1, 0) == -1) {
perror("server msgsnd");
exit(1);
}
}
msgctl(msgqid, IPC_RMID, 0);
exit(0);
}
int main() {
msgqid = msgget(MSGKEY, 0777 | IPC_CREAT);
if(msgqid == -1) {
perror("main msgget");
return 1;
}
if(fork()) { // Parent process, becomes server
SERVER();
} else { // Child process, becomes client
CLIENT();
}
// Since the parent doesn't fork again and directly calls SERVER(),
// there's no need for additional waits as in the original code.
return 0;
}