c - 代码错误 : message queue not receiving the value

标签 c posix

我的队列正在发送消息,但没有收到...

任何人都可以帮忙解决这个问题吗?

编者注:改进了代码格式,但需要更多详细信息

<小时/>

代码:

#define MAXSIZE     128

void die(char *s)
{
  perror(s);
  exit(1);
}

struct msgbuf
{
    int    mtype;
    char    mtext[MAXSIZE];
};

-> main()

main()
{
    int msqid;
    int msgflg = IPC_CREAT | 0666;
    key_t key;
    struct msgbuf sbuf;
     struct msgbuf rcvbuffer;
    int buflen;
    srand(time(0));
    key = rand()%(100+40);
    printf("%d",key);

获取给定键的消息队列ID

    if ((msqid = msgget(key, msgflg )) < 0)   //Get the message queue ID for the given key
      die("msgget");

    //Message Type
    sbuf.mtype = 1;

    printf("Enter a message to add to message queue : ");
    scanf("%[^\n]",sbuf.mtext);
    getchar();

    buflen = strlen(sbuf.mtext) + 1 ;

    if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
    {
       printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buflen);
        die("msgsnd");
    }

    else
        printf("Message Sent\n");
    printf("%d",msqid);
    exit(0);


    if ((msqid = msgget(key, 0666)) < 0)
      die("msgget()");

接收消息类型 1 的应答。

     //Receive an answer of message type 1.
    if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
      die("msgrcv");

    printf("%s\n", rcvbuffer.mtext);
}

谢谢

最佳答案

我花了一些时间,但我发现了你的错误。消息队列的类型检查取决于 long 类型而不是 int 类型的 mtype 字段。

如果您只是接收消息而不指定类型,那么消息就会通过。但如果您指定类型,则不会,因为“struct msgbuf”中的“mtype”字段是 int 类型而不是 long 类型。 (在我的 - 很可能也是你的 - 架构上,两者之间有 4 个字节的差异)

将 struct msgbuf 中的 mtype 类型更改为 long,它将起作用...

关于c - 代码错误 : message queue not receiving the value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23169516/

相关文章:

c++ - 为什么库链接器标志有时必须在最后使用 GCC?

c - char *a[]= {"hello", "world"}; 之间有什么区别?和 char a[][10]= {"hello", "world"};?

c - 链表添加删除功能失效

连接键盘输入的两个字符串

c - 如何在 __asm__ 中使用 int?

file-io - 为什么命名管道的只读打开会阻塞?

c++ - free() 在传递由 posix_memalign() 创建的有效指针时挂起 - gcc 和 C++11

c - 从 POSIX I/O(open 等)迁移到 C 标准 I/O(fopen 等)

c - POSIX 方式将用户输入的 utc 偏移量转换为日历时间

位运算符可以有未定义的行为吗?