利用消息队列实现ECHO_SRV

本文详细介绍了使用消息队列进行进程间通信的实现方法,包括server端和client端的代码示例,展示了如何通过设置mtype来区分不同的消息类型,实现数据的发送与接收。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

server端代码:

server 从队列的mtype=1接收数据 在发到mtype=pid(client的进程id)



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#define MSGMAX 8192
#define ERR_EXIT(m) \
    do { \
        perror(m);\
        exit(EXIT_FAILURE);\
    }while(0)

struct msgbuf{
    long mtype;
    char mtext[MSGMAX];   //消息缓冲区
};


void echo_srv(int msgid)
{
    int n;
    struct msgbuf msg;
    memset(&msg, 0, sizeof(msg));
    while(1)
    {
        if((n = msgrcv(msgid, &msg, MSGMAX, 1, 0)) <0)
            ERR_EXIT("msgsnd");
        int pid;
        pid = *((int*)msg.mtext);

        fputs(msg.mtext+4, stdout);
        msg.mtype = pid;
        msgsnd(msgid, &msg, n, 0);
    }
}

int main(int argc, const char *argv[])
{
    int msgid;
    msgid = msgget(1111, 0);
    if(msgid == -1)
        ERR_EXIT("msgget");
    echo_srv(msgid);

    printf("read \n");
    return 0;
}

 

client端:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#define MSGMAX 8192
#define ERR_EXIT(m) \
    do { \
        perror(m);\
        exit(EXIT_FAILURE);\
    }while(0)

struct msgbuf{
    long mtype;
    char mtext[MSGMAX];   //消息缓冲区
};




void echo_cli(int msgid)
{
    int pid;
    pid = getpid();
    struct msgbuf msg;
    memset(&msg, 0, sizeof(msg));
    msg.mtype = 1;
    *(int*)msg.mtext = pid;
    while(fgets(msg.mtext+4, MSGMAX, stdin) != NULL)
    {
//        msg.mtype = 1;
        if((msgsnd(msgid, &msg, 4+strlen(msg.mtext+4), IPC_NOWAIT)) <0)
            ERR_EXIT("msgsnd");
//
        memset(msg.mtext+4, 0, MSGMAX);
        if((msgrcv(msgid, &msg, MSGMAX, pid, 0)) <0)
            ERR_EXIT("msgrcv");

        fputs(msg.mtext+4, stdout);
        memset(msg.mtext+4, 0, MSGMAX-4);
    }

}


int main(int argc, const char *argv[])
{
    int msgid;
    msgid = msgget(1111, 0);
    if(msgid == -1)
        ERR_EXIT("msgget");
    
    echo_cli(msgid);

    return 0;
}

就是这个套路,熟练即可

转载于:https://www.cnblogs.com/DLzhang/p/4307398.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值