【问题标题】:Message queue error: No message of desired type消息队列错误:没有所需类型的消息
【发布时间】:2017-06-14 10:43:58
【问题描述】:

我正在尝试了解消息队列的工作原理。我创建了这个小程序,其中子进程向父进程发送消息。大多数时候,它有效,但有时我会收到错误:Error parent: No message of desired type。我还尝试wait 以完成子进程,但我仍然会收到错误消息。

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

int main(){

    struct msg{
        long mtype;
        char text[100];
    };

    int key = ftok(".", 10);
    int qid = msgget(key, 0666|IPC_CREAT);

    int pid = fork();

    if(pid == 0){
        struct msg send;
        send.mtype = 1;
        strcpy(send.text, "hello");
        if(msgsnd(qid, (void*)&send, strlen(send.text), IPC_NOWAIT)<0){
             printf("Error child: ");
        }
    }
    else{
        struct msg recieve;
        if(msgrcv(qid, (void*)&recieve, 100, 1, IPC_NOWAIT)<0){
             perror("Error parent: ");
        };
        printf("%s\n", recieve.text);
    }

    return 0;
}

谢谢。

【问题讨论】:

    标签: c unix message-queue


    【解决方案1】:

    http://pubs.opengroup.org/onlinepubs/7908799/xsh/msgrcv.html

    参数 msgflg 指定在所需类型的消息不在队列中时要执行的操作。它们如下:

    • 如果 (msgflg & IPC_NOWAIT) 不为零,则调用线程将立即返回,返回值为 -1 且 errno 设置为 [ENOMSG] ...

    您指定了IPC_NOWAIT,这意味着您没有给子进程足够的时间来生成任何消息。如果你从参数msgflg 中删除它,即

    if(msgrcv(qid, (void*)&recieve, 100, 1, 0) < 0)
    

    父进程将阻塞,直到队列中有可用的东西。

    【讨论】:

      猜你喜欢
      • 2012-06-03
      • 2011-02-21
      • 2014-04-08
      • 2013-07-18
      • 1970-01-01
      • 2019-05-29
      • 2012-07-06
      • 1970-01-01
      • 2011-05-23
      相关资源
      最近更新 更多