此代码不一定可以使用!!!因为其实我自己都没有搞清楚很多东西。
用户端
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define SVKEY 1234
#define REQ 1
#define RESP 2
struct msgbuf {
long mtype;
pid_t pid;
};
int main() {
int msqid;
struct msgbuf buf;
// 获取消息队列
if ((msqid = msgget(SVKEY, 0666)) == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}
// 发送请求消息
buf.mtype = REQ;
buf.pid = getpid();
if (msgsnd(msqid, &buf, sizeof(pid_t), 0) == -1) {
perror("msgsnd");
exit(EXIT_FAILURE);
}
// 接收应答消息
if (msgrcv(msqid, &buf, sizeof(pid_t), getpid(), 0) == -1) {
perror("msgrcv");
exit(EXIT_FAILURE);
}
printf("Received reply from server %d\n", buf.pid);
return 0;
}
服务端
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define SVKEY 1234
#define REQ 1
#define RESP 2
struct msgbuf {
long mtype;
pid_t pid;
};
int main() {
int msqid;
struct msgbuf buf;
// 创建消息队列
if ((msqid = msgget(SVKEY, IPC_CREAT | 0666)) == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}
// 服务端循环接收请求消息
while (1) {
// 接收请求消息
if (msgrcv(msqid, &buf, sizeof(pid_t), REQ, 0) == -1) {
perror("msgrcv");
exit(EXIT_FAILURE);
}
printf("Serving for client %d\n", buf.pid);
// 发送应答消息
buf.mtype = buf.pid;
buf.pid = getpid();
if (msgsnd(msqid, &buf, sizeof(pid_t), 0) == -1) {
perror("msgsnd");
exit(EXIT_FAILURE);
}
}
return 0;
}