• 利用消息队列实现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;
    }

    就是这个套路,熟练即可

  • 相关阅读:
    网页性能分析
    vue学习图解
    px-em-rem单位转换
    呼啦圈(keyframes和transform结合)
    菜单栏鼠标经过伸缩效果
    携程transform放大效果
    浮动布局demo
    倒圆角艺术
    伪类分类
    ingress-nginx 添加https证书
  • 原文地址:https://www.cnblogs.com/DLzhang/p/4307398.html
Copyright © 2020-2023  润新知