linux 消息队列类型

来源:互联网 发布:facebook自动加人软件 编辑:程序博客网 时间:2024/06/13 14:32

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 1000int 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 1000int 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);}


0 0