IPC message queue demo

// .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
// 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");
}
//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,主要是数量,读完后会删除这样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值