Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 消息队列错误:没有所需类型的消息_C_Unix_Message Queue - Fatal编程技术网

C 消息队列错误:没有所需类型的消息

C 消息队列错误:没有所需类型的消息,c,unix,message-queue,C,Unix,Message Queue,我试图了解消息队列是如何工作的。我创建了这个小程序,其中子进程向父进程发送消息。大多数情况下,它是有效的,但有时我会收到错误:error parent:No message of required type。我还尝试等待子进程完成,但仍然会出现错误 #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stri

我试图了解消息队列是如何工作的。我创建了这个小程序,其中子进程向父进程发送消息。大多数情况下,它是有效的,但有时我会收到错误:
error parent:No message of required type
。我还尝试
等待子进程完成,但仍然会出现错误

#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main(){
结构味精{
长型;
字符文本[100];
};
int key=ftok(“.”,10);
int qid=msgget(键,0666 | IPC|U CREAT);
int-pid=fork();
如果(pid==0){
结构消息发送;
send.mtype=1;
strcpy(send.text,“hello”);
如果(msgsnd(qid,(void*)和send,strlen(send.text),IPC_NOWAIT)

参数msgflg指定当所需类型的消息不在队列中时要采取的操作。如下所示:

  • 如果(msgflg&IPC_NOWAIT)非零,调用线程将立即返回,返回值为-1,errno设置为[ENOMSG]
您正在指定
IPC\u NOWAIT
,这意味着您没有给子进程足够的时间生成任何消息。如果您从参数
msgflg
中删除该参数,即

if(msgrcv(qid, (void*)&recieve, 100, 1, 0) < 0)
if(msgrcv(qid,(void*)&receive,100,1,0)<0)
父进程将阻塞,直到队列中有可用的内容