• 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;
    }
    

      

      

      

  • 相关阅读:
    Object之克隆对象clone 和__clone()函数
    Object之魔术函数__toString() 直接输出对象引用时自动调用
    Object之魔术函数__call() 处理错误调用
    Git关联远程GitHub仓库
    python制作查找单词翻译的脚本
    用python处理文本,本地文件系统以及使用数据库的知识基础
    基于序列化技术(Protobuf)的socket文件传输
    Python核心编程——Chapter16
    gdb初步窥探
    unp学习笔记——Chapter1
  • 原文地址:https://www.cnblogs.com/luckygxf/p/12303142.html
Copyright © 2020-2023  润新知