日期:2014-05-16  浏览次数:20630 次

一个消息队列例子,第一次运行正确,第二次运行就提示消息发送失败了
第一次运行还能正确发送消息,第二次运行就无法发出消息,请大家指点下,谢谢。
C/C++ code

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
    key_t unique_key;
    int msgid;
    int status;
    char str1[] = {"test message:hello!"};
    char str2[] = {"test message:goodbye!"};
    struct msgbuf
    {
        long msgtype;
        char msgtext[1024];
    }sndmsg,rcvmsg;

    if(msgid = msgget(IPC_PRIVATE, 0666) == -1)
    {
        printf("msgget error!\n");
        exit(254);
    }

    sndmsg.msgtype = 111;
    sprintf(sndmsg.msgtext, "%s", str1);

    if(msgsnd(msgid, (struct msgbuf *)&sndmsg, sizeof(str1)+1, 0) == -1)
    {
        printf("msgtype 111 send error!\n");
        exit(254);
    }

    if(status = msgrcv(msgid, (struct msgbuf *)&rcvmsg,80,111,IPC_NOWAIT) == -1)
    {
        printf("msgrcv error!\n");
        exit(254);
    }

    printf("The received message:%s\n",rcvmsg.msgtext);
    msgctl(msgid, IPC_RMID, 0);

    exit(0);
}



------解决方案--------------------
改成if( ( msgid=(msgget(IPC_PRIVATE, 0660))) == -1)

ipcs -qa 就发现异常了,一下子多了那么多队列
------解决方案--------------------
嗯,典型的C语法错误
if((msgid = msgget(IPC_PRIVATE, 0666)) == -1)
------解决方案--------------------
sizeof(str1)+1 这不对哦,不需要+1,不过你这里是先拷贝过去的,多发也不是越界而已。
------解决方案--------------------
if(msgid = msgget(IPC_PRIVATE, 0666) == -1)
少加了括号,应该是if((msgid = msgget(IPC_PRIVATE, 0666)) == -1)