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

相关推荐
技术炼丹人20 分钟前
从RNN为什么长依赖遗忘到注意力机制的解决方案以及并行
人工智能·python·算法
NfN-sh39 分钟前
计数组合学7.12( RSK算法的一些推论)
笔记·学习·算法
ikkkkkkkl1 小时前
LeetCode:15.三数之和&&18.四数之和
c++·算法·leetcode
屁股割了还要学1 小时前
【数据结构入门】链表
c语言·开发语言·数据结构·c++·学习·算法·链表
Mr数据杨1 小时前
数据与模型优化随机森林回归进行天气预测
算法·随机森林·回归
chen1112 小时前
有关人工智能(AI)的搜索算法(CS50)
算法
恣艺2 小时前
LeetCode 135:分糖果
算法·leetcode·职场和发展
TDengine (老段)2 小时前
TDengine 中 TDgp 中添加算法模型(异常检测)
java·大数据·数据库·算法·时序数据库·tdengine·涛思数据
2501_924748243 小时前
高密度客流识别精度↑32%!陌讯多模态融合算法在智慧交通的实战解析
大数据·人工智能·算法·目标检测·计算机视觉
WeiJingYu.3 小时前
逻辑回归的应用
算法·机器学习·逻辑回归