首页 > 其他 > 详细

c 消息队列

时间:2020-02-13 13:40:37      阅读:56      评论:0      收藏:0      [点我收藏+]

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\n");
        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\n", 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\n", res);
    res = msgrcv(msgId, &msginfo2Send, 256, 124, 0);
    printf("receive from msgserver:%s\n", msginfo2Send.content);
    printf("msgrcv res:%d\n", res);

    return 0;
}

  

  

  

c 消息队列

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!