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,主要是数量,读完后回删除这样

相关推荐
黄俊懿3 分钟前
【深入理解SpringCloud微服务】手写实现各种限流算法——固定时间窗、滑动时间窗、令牌桶算法、漏桶算法
java·后端·算法·spring cloud·微服务·架构
新缸中之脑3 分钟前
Llama 3.2 安卓手机安装教程
前端·人工智能·算法
夜雨翦春韭23 分钟前
【代码随想录Day29】贪心算法Part03
java·数据结构·算法·leetcode·贪心算法
Curry_Math40 分钟前
Acwing 区间DP & 计数类DP
算法
Tisfy1 小时前
LeetCode 1928.规定时间内到达终点的最小花费:动态规划
算法·leetcode·动态规划·
ん贤1 小时前
贪心算法.
算法·贪心算法
cndes1 小时前
大数据算法的思维
大数据·算法·支持向量机
睡不着还睡不醒3 小时前
【数据结构强化】应用题打卡
算法
sp_fyf_20243 小时前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-10-05
人工智能·深度学习·神经网络·算法·机器学习·语言模型·自然语言处理
C++忠实粉丝4 小时前
前缀和(6)_和可被k整除的子数组_蓝桥杯
算法