IPC message queue demo

cpp 复制代码
// .h

#ifndef __IPCCOMMON_H__
#define __IPCCOMMON_H__
#define MSGKEY   1234
#define MAX_TEXT 512
#define MSG_TYPE 111

typedef struct _mymesg
{
    long int type;
    char context[MAX_TEXT];
}mymsg;
#endif
cpp 复制代码
// create and send

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>


#include <sys/msg.h>
#include "ipccommon.h"

int main(void)
{
    struct msqid_ds info;
    int tempMsgId;
    char tempPayload = 0;

    mymsg tmpMsgData;

    printf("ipc send demo\n");
    tempMsgId = msgget((key_t)MSGKEY, 0666 | IPC_CREAT);  
    if (tempMsgId == -1)
    {
        printf("error create\n");
    }
    int loop = 0;
    tmpMsgData.type = MSG_TYPE;

    while ( loop++ < 11)
    {
        tmpMsgData.context[0] = tempPayload++;    
        if(-1 == (msgsnd(tempMsgId, (void*)&tmpMsgData, sizeof(tempPayload), 0)))
        {
            printf("erro send\n");
            
        }
        printf("snd num %d\n", loop);
        sleep (1);
    }

    sleep(10);
    exit(0);
    printf("ipc send demo finished\n");
}
cpp 复制代码
//rev and ctl

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>


#include <sys/msg.h>
#include "ipccommon.h"


int main(void)
{
    struct msqid_ds info;
    int tempMsgId;
    char tempPayload = 0;

    char tmpMsgData[sizeof(mymsg)];
    printf("ipc rev demo\n");

    tempMsgId = msgget((key_t)MSGKEY, 0666 | IPC_CREAT);  
    if (tempMsgId == -1)
    {
        printf("error create\n");
    }

    msgctl(tempMsgId, IPC_STAT, &info);
    printf("msg info.number %ld\n", info.msg_qnum);
    
    int loop = 0;
    while ( loop++ < info.msg_qnum)
    {
        if(-1 == (msgrcv(tempMsgId, (void*)&tmpMsgData, MAX_TEXT, MSG_TYPE, 0)))
        {
            printf("erro rev\n");
        }
        printf("rev %d num\n", loop);

        mymsg* pmsg = (mymsg*)tmpMsgData;
        printf("rev: type is %ld, value is %d\n", pmsg->type, pmsg->context[0]);

        sleep (1);
    }
   
    msgctl(tempMsgId, IPC_STAT, &info);
    if (info.msg_qnum == 0)
    {
        printf("msg empty try to delete\n");
        if (0 == msgctl(tempMsgId, IPC_RMID, NULL))
        {
            printf("successfully delete the tempMsgId\n");
        }
    }
    printf("ipc rev demo finished\n");
}

先运行create send部分,可以分开执行,也可以同时执行,目前是阻塞。

再执行rev部分。rcv 会读取目前msg info,主要是数量,读完后回删除这样

相关推荐
mjhcsp13 分钟前
C++ 循环结构:控制程序重复执行的核心机制
开发语言·c++·算法
立志成为大牛的小牛13 分钟前
数据结构——四十一、分块查找(索引顺序查找)(王道408)
数据结构·学习·程序人生·考研·算法
xier_ran30 分钟前
深度学习:RMSprop 优化算法详解
人工智能·深度学习·算法
地平线开发者39 分钟前
不同传感器前中后融合方案简介
算法·自动驾驶
地平线开发者1 小时前
征程 6X 常见 kernel panic 问题
算法·自动驾驶
com_4sapi2 小时前
2025 权威认证头部矩阵系统全景对比发布 双榜单交叉验证
大数据·c语言·人工智能·算法·矩阵·机器人
前端小L2 小时前
二分查找专题(九):“降维”的魔术!将二维矩阵“拉平”为一维
数据结构·算法
Jasmine_llq2 小时前
《P7516 [省选联考 2021 A/B 卷] 图函数》
算法·弗洛伊德算法·floydwarshall算法·后缀和计算
kaikaile19952 小时前
三维CT图像重建算法
算法
她说人狗殊途2 小时前
时间复杂度(按增长速度从低到高排序)包括以下几类,用于描述算法执行时间随输入规模 n 增长的变化趋势:
数据结构·算法·排序算法