zoukankan      html  css  js  c++  java
  • 利用消息队列实现ECHO_SRV

    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 
    ");
        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;
    }

    就是这个套路,熟练即可

  • 相关阅读:
    【学习笔记】一:JavaScript简介
    【学习笔记】Sass入门指南
    【学习笔记】前端开发面试锦集
    庆祝我的博客园正式开张
    python解析AMF协议
    C语言setjmp函数使用
    CONTAINING_RECORD 宏
    samba的安装及其使用
    confluence的安装
    查看mysql字符集及修改表结构--表字符集,字段字符集
  • 原文地址:https://www.cnblogs.com/DLzhang/p/4307398.html
Copyright © 2011-2022 走看看