用system v消息队列实现回射客户/服务器程序

本文提供了一组基于消息队列实现的客户端和服务端程序示例代码,详细展示了客户端和服务端如何通过消息队列进行双向通信的过程。

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

客户端程序

#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<sys/un.h>
#include<fcntl.h>
#include<sys/msg.h>
#define ERR_EXIT(m)\
    do\
    {\
        perror(m);\
        exit(EXIT_FAILURE);\
    }while(0)
#define MSGMAX 8192
struct msgbuf{
    long mtype;
    char mtext[1];
};
void echo_cli(int msgid)
{
    int pid;
    int n;
    pid=getpid();
    struct msgbuf msg;
    memset(&msg,0,sizeof(msg));
    *((int *)msg.mtext)=pid;
    msg.mtype=1;
    while(fgets(msg.mtext+4,MSGMAX,stdin)!=NULL)
    {
        if(msgsnd(msgid,&msg,4+strlen(msg.mtext+4),0)<0)
            ERR_EXIT("msgsnd");
        memset(msg.mtext+4,0,MSGMAX-4);
        if((n=msgrcv(msgid,&msg,MSGMAX,pid,0))<0)
            ERR_EXIT("msgsnd");
        fputs(msg.mtext+4,stdout);
        memset(msg.mtext+4,0,MSGMAX-4);
    }
}

int main(void)
{
    int msgid;
    msgid=msgget(1234,0);
    if(msgid==-1)
    {
        ERR_EXIT("msgget");
    }
    echo_cli(msgid);    
    return 0;
}

 

服务端程序:

#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<sys/un.h>
#include<fcntl.h>
#include<sys/msg.h>
#define ERR_EXIT(m)\
    do\
    {\
        perror(m);\
        exit(EXIT_FAILURE);\
    }while(0)
#define MSGMAX 8192
struct msgbuf{
    long mtype;
    char mtext[1];
};
void echo_srv(int msgid)
{
    int n;
    struct msgbuf msg;
    memset(&msg,0,sizeof(msg));
    while(1)
    {
        //客户端发过来的都是类型为1的消息
        if((n=msgrcv(msgid,&msg,MSGMAX,1,0))<0)
            ERR_EXIT("msgrcv");
        int pid;
        pid=*((int *)msg.mtext);
        fputs(msg.mtext+4,stdout);
        msg.mtype=pid;
        msgsnd(msgid,&msg,n,0);

    }
}
int main(void)
{
    int msgid;
    msgid=msgget(1234,IPC_CREAT|0666);
    if(msgid==-1)
        ERR_EXIT("msgget");
    echo_srv(msgid);        
    return 0;
}

 

转载于:https://www.cnblogs.com/wsw-seu/p/8555292.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值