linux乒乓通信

测试代码

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值