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

相关推荐
DoraBigHead36 分钟前
小哆啦解题记——异位词界的社交网络
算法
木头左2 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
lifallen6 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree
web_Hsir8 小时前
vue3.2 前端动态分页算法
前端·算法
地平线开发者10 小时前
征程 6M 部署 Omnidet 感知模型
算法·自动驾驶
秋说11 小时前
【PTA数据结构 | C语言版】线性表循环右移
c语言·数据结构·算法
浩瀚星辰202411 小时前
图论基础算法:DFS、BFS、并查集与拓扑排序的Java实现
java·算法·深度优先·图论
oioihoii14 小时前
C++随机打乱函数:简化源码与原理深度剖析
开发语言·c++·算法
不知名。。。。。。。。14 小时前
分治算法---快排
算法
minji...14 小时前
数据结构 算法复杂度(1)
c语言·开发语言·数据结构·算法