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

客户端程序

#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