[国嵌攻略][086][消息队列通讯]

消息队列

消息队列就是一个消息的链表。而一条消息则可以看作一个记录,具有特定的格式。进程可以向中按照一定的规则添加新消息;另一些进程则可以从消息队列中读走消息。

消息格式

每一条消息都有固定的格式。格式如下:

struct msgbuf {

long mtype;       /* message type, must be > 0 */

char mtext[1];    /* message data */

};

A.c

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

typedef struct msgbuf {
    long mtype;       /* message type, must be > 0 */
    char mtext[1024]; /* message data */
}MsgBuf;

void main(){
    //创建消息队列
    int key;
    int msqid;
    
    key = ftok("./", 0);
    msqid = msgget(key, IPC_CREAT);
    
    while(1){
        //获取消息类型
        long mtype;
        
        printf("Message Type:");
        scanf("%d", &mtype);
        
        //判断是否退出
        if(mtype == 0){
            break;
        }
        
        //获取消息数据
        char mtext[1024];
        
        printf("Message Text:");
        scanf("%s", mtext);
        
        //发送消息结构
        MsgBuf msgBuf;
        
        msgBuf.mtype = mtype;
        strcpy(msgBuf.mtext, mtext);
        
        msgsnd(msqid, &msgBuf, sizeof(MsgBuf), 0);
    }
    
    //删除消息队列
    msgctl(msqid, IPC_RMID, NULL);
}

B.c

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

typedef struct msgbuf {
    long mtype;       /* message type, must be > 0 */
    char mtext[1024]; /* message data */
}MsgBuf;

void process(int msqid);

void main(){
    //打开消息队列
    int key;
    int msqid;
    
    key = ftok("./", 0);
    msqid = msgget(key, IPC_EXCL);
    
    //创建处理进程
    int i;
    
    for(i = 0; i < 3; i++){
        int pid;
        
        pid = fork();
        if(pid == 0){
            process(msqid);
        }
    }
}

void process(int msqid){
    while(1){
        //接收消息
        MsgBuf msgBuf;
        
        msgrcv(msqid, &msgBuf, sizeof(MsgBuf), 0, 0);
        
        //显示消息
        printf("Message Text:%s
", msgBuf.mtext);
    }
}
原文地址:https://www.cnblogs.com/d442130165/p/5227854.html