• 消息队列 两个进程


    参考地址:http://blog.csdn.net/zhsp1029/article/details/2171462

    /*msgserver.c*/

    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    #include <sys/stat.h>

    #define MSG_FILE "/tmp/msg_logs"
    #define BUFFER 255
    #define PERM S_IRUSR|S_IWUSR
    /* 服务端创建的消息队列最后没有删除,我们要使用ipcrm命令来删除的 */
    /* ipcrm -q <msqid> */

    struct msgtype {
    long mtype;
    char buffer[BUFFER+1];
    };

    int main()
    {
    struct msgtype msg;
    key_t key;
    int msgid;

    if((key=ftok(MSG_FILE,'a'))==-1)
    {
    printf("Creat Key Error:%s/n", strerror(errno));
    exit(1);
    }

    if((msgid=msgget(key, PERM|IPC_CREAT|IPC_EXCL))==-1)
    {
    printf("Creat Message Error:%s/n", strerror(errno));
    exit(1);
    }
    printf("msqid = %d/n", msgid);

    //while(1)
    {
    msgrcv(msgid, &msg, sizeof(struct msgtype), 1, 0);
    printf("Server Receive:%s/n", msg.buffer);
    msg.mtype = 2;
    msgsnd(msgid, &msg, sizeof(struct msgtype), 0);
    if((msgctl(msgid,IPC_RMID,NULL))<0){ //删除消息
    perror("msgctl");
    exit(1);
    }
    }


    exit(0);
    }




    /* msgclient.c */

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    #include <sys/stat.h>

    #define MSG_FILE "/tmp/msg_logs"
    #define BUFFER 255
    #define PERM S_IRUSR|S_IWUSR

    struct msgtype {
    long mtype;
    char buffer[BUFFER+1];
    };

    int main(int argc, char **argv)
    {
    struct msgtype msg;
    key_t key;
    int msgid;

    if(argc != 2)
    {
    fprintf(stderr,"Usage:%s string/n", argv[0]);
    exit(1);
    }

    if((key=ftok(MSG_FILE,'a'))==-1)
    {
    fprintf(stderr,"Creat Key Error:%s/n", strerror(errno));
    exit(1);
    }

    if((msgid=msgget(key, PERM))==-1)
    {
    fprintf(stderr,"Creat Message Error:%s/n", strerror(errno));
    exit(1);
    }

    msg.mtype = 1;
    strncpy(msg.buffer, argv[1], BUFFER);
    msgsnd(msgid, &msg, sizeof(struct msgtype), 0);
    memset(&msg, '/0', sizeof(struct msgtype));
    msgrcv(msgid, &msg, sizeof(struct msgtype), 2, 0);
    fprintf(stderr, "Client receive:%s/n", msg.buffer);
    exit(0);
    }



  • 相关阅读:
    约数的问题
    广度搜索基本逻辑
    奇葩概念
    一枚前端UI组件库 KUI for React
    一枚前端UI组件库 KUI for Vue
    跨域的常见问题和解决方案
    Comet,SSE,WebSocket前后端的实现
    web渐进式应用PWA
    IIS 部署node
    javascript 时间戳
  • 原文地址:https://www.cnblogs.com/wangkangluo1/p/2287576.html
Copyright © 2020-2023  润新知