• 基于内存的通信之一 “内核共享消息队列”


    编程步骤:

    1.创建共享消息队列/得到消息队列

    2.操作消息队列(发送、接收等)

      

    3.删除队列

    案例应用:

    创建两个进程A、B

    其中A 如下:

    #include <unistd.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    struct msgbuf
    {
        long type;
        char data[32];
    };
    main()
    {
        key_t key;
        int msgid;
        int i;
        struct msgbuf msg;
        
        //1创建消息队列
        key=ftok(".",200);
        if(key==-1) printf("ftok err:%m
    "),exit(-1);
        
        msgid=msgget(key,0/*IPC_CREAT|IPC_EXCL|0666*/);
        if(msgid==-1)printf("get err:%m
    "),exit(-1);
        //2构造消息
            
        //3发送消息
        for(i=1;i<=10;i++)
        {
            bzero(msg.data,sizeof(msg.data));
            msg.type=1;
            sprintf(msg.data,"MessageI:%d",i);
            msgsnd(msgid,&msg,sizeof(msg.data),0);
        }
        for(i=1;i<=10;i++)
        {
            bzero(msg.data,sizeof(msg.data));
            msg.type=2;
            sprintf(msg.data,"MessageII:%d",i);
            
            msgsnd(msgid,&msg,sizeof(msg.data),0);
        }
        //4删除队列
        //msgctl(msgid,IPC_RMID,0);
    }

    B进程如下:

    #include <unistd.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    struct msgbuf
    {
        long type;
        char data[32];
    };
    main()
    {
        key_t key;
        int msgid;
        int i;
        struct msgbuf msg;
        //1得到消息队列
        key=ftok(".",200);
        if(key==-1) printf("ftok err:%m
    "),exit(-1);
        
        msgid=msgget(key,0);
        if(msgid==-1)printf("get err:%m
    "),exit(-1);
        //2构造消息
            
        //3接收消息
        while(1)
        {
            bzero(&msg,sizeof(msg));
            msg.type=2;
            msgrcv(msgid,&msg,sizeof(msg.data),2,0);
            printf("%s
    ",msg.data);
        }
        
    }
  • 相关阅读:
    【4】通过简化的正则表达式处理字符串
    水晶报表WEB方式下不打印的问题
    字符串处理总结(旧)
    【3】利用Word模板生成文档的总结
    这个教授的观点颇犀利
    互联网时代还需要看书吗?
    怎样更爽地看PDF杂志
    吐槽win7
    信息技术真有想象的那么靠谱吗?
    无线路由器桥接的设置
  • 原文地址:https://www.cnblogs.com/huacw/p/3581766.html
Copyright © 2020-2023  润新知