linux 消息队列类型

本文介绍了一个针对Linux消息队列的发送端测试案例,该案例通过循环发送不同类型的消息来验证消息队列的行为。特别指出,消息类型不能设置为0,否则会导致invalid argument错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

linux消息队列类型不能为0,否则将会报invalid argument错误。测试代码如下,如果发送端循环从0开始将出现错误。

send.cc

/*=============================================================================
#      Filename : send.cc
#   Description : 发送端实现
#        Author : chenqingming chenqingming0710@163.com
#        create : 2014-03-20 20:48
# Last modified : 2014-03-20 20:48
=============================================================================*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <string.h>

#include "data_type.hpp"

#define SEND_COUNT 1000

int main()
{
    int status = -1;
    int msg_id = -1;
    int i;
    key_t ipc_key = (key_t)-1;

    //获取键值
    ipc_key = get_ipc_key();
    if (ipc_key == (key_t)-1)
    {
        fputs("get ipc_id fail\n", stdout);
        exit(1);
    }

    //创建消息队列
    msg_id = msgget(ipc_key, 0777|IPC_CREAT);
    if (msg_id == -1)
    {
        fputs("create msg fail\n", stdout);
        exit(2);
    }

    //发送消息
    msg_struct msg_data;
    for (i = 0; i < SEND_COUNT; ++i)
    {
        msg_data.msg_type = i+1;
        int j;
        for (j = 0; j < i + 1; ++j)
        {
            msg_data.msg[j] = 'A';
        }
        msg_data.msg[j] = '\0';

        //send
        status = msgsnd(msg_id, (void*)&msg_data, MAX_MSG_LENGTH, 0);
        if (status == -1)
        {
            printf("%s\n", strerror(errno));
            fputs("send error\n", stdout);
            exit(1);
        }
    }
    fputs("send over\n", stdout);
    exit(EXIT_SUCCESS);
}

get.cc

#include <stdio.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <sys/ipc.h>

#include "data_type.hpp"
#define GET_COUNT 1000

int main()
{
    key_t ipc_id = get_ipc_key();
    if (ipc_id == (key_t)-1)
      exit(1);

    int msg_id = msgget(ipc_id, 0777|IPC_CREAT);
    if (msg_id == -1)
      exit(2);

    msg_struct msg_data;
    fputs("start gen msg\n", stdout);
    while (1)
    {
        if (msgrcv(msg_id, &msg_data, MAX_MSG_LENGTH, 0, 0) == -1)
          exit(2);

        printf("%ld\n", msg_data.msg_type);
        //fputs(msg_data.msg, stdout);
        if (msg_data.msg_type == GET_COUNT - 1)
          break;
    }
    
    printf("get over :%ld\n", msg_data.msg_type);
    exit(EXIT_SUCCESS);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值