c 消息队列

1. 使用头文件<sys/msg.h>

2. ftok函数获取key,内核使用key作为唯一标识创建消息队列

3. msgsnd, msgrcv函数,发送/接收消息

4. 消息结果第一个字段要为long type

ipc-msg.h

//
// Created by gxf on 2020/2/13.
//

#ifndef UNTITLED_IPC_MSGQUEUE_H
#define UNTITLED_IPC_MSGQUEUE_H

#define FTOK_FILE "/etc/passwd"
const int ftok_pro = 'z';
typedef struct{
    long type;
    char content[256];
} msginfo;

#endif //UNTITLED_IPC_MSGQUEUE_H

server.c

//
// Created by gxf on 2020/2/13.
//
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/msg.h>

#include "ipc-msgqueue.h"

int main() {
    key_t ftokRes = ftok(FTOK_FILE, ftok_pro);
    if (ftokRes < 0) {
        printf("ftok err
");
        return 1;
    }

    int msgId = msgget(ftokRes, IPC_CREAT | 0777);
    if (msgId < 0) {
        perror("msgget fail");
        return 1;
    }
    msginfo recveivMsgInfo;
    while (1) {
        msgrcv(msgId, &recveivMsgInfo, 256, 123, 0);
        printf("receive from client msg:%s
", recveivMsgInfo.content);
        recveivMsgInfo.type = 124;
        msgsnd(msgId, &recveivMsgInfo, 256, 0);
    }

    return 0;
}

client.c

//
// Created by gxf on 2020/2/13.
//

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/msg.h>

#include "ipc-msgqueue.h"

int main() {
    key_t ftokRes = ftok(FTOK_FILE, ftok_pro);
    if (ftokRes < 0) {
        perror("ftok fail");
        return 1;
    }
    msginfo msginfo2Send;
    msginfo2Send.type = 123;
    sprintf(msginfo2Send.content, "hello I am client pid:%d", getpid());

    int msgId = msgget(ftokRes, IPC_CREAT | 777);
    if (msgId < 0) {
        perror("msgget fail");
        return 0;
    }

    int res = msgsnd(msgId, &msginfo2Send, 256, 0);
    printf("msgsnd res:%d
", res);
    res = msgrcv(msgId, &msginfo2Send, 256, 124, 0);
    printf("receive from msgserver:%s
", msginfo2Send.content);
    printf("msgrcv res:%d
", res);

    return 0;
}

  

  

  

原文地址:https://www.cnblogs.com/luckygxf/p/12303142.html