Message queue error: No message of desired type
Message queue error: No message of desired type
我正在尝试了解消息队列的工作原理。我创建了这个小程序,其中子进程向父进程发送消息。大多数时候,它都有效,但有时我会收到错误消息: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;
}
谢谢。
http://pubs.opengroup.org/onlinepubs/7908799/xsh/msgrcv.html
The argument msgflg specifies the action to be taken if a message of the desired type is not on the queue. These are as follows:
- If (msgflg & IPC_NOWAIT) is non-zero, the calling thread will return immediately with a return value of -1 and errno set to [ENOMSG]
...
您正在指定 IPC_NOWAIT
,这意味着您没有给子进程足够的时间来生成任何消息。如果您从参数 msgflg
中删除它,即
if(msgrcv(qid, (void*)&recieve, 100, 1, 0) < 0)
父进程将阻塞,直到队列中有可用的东西。
我正在尝试了解消息队列的工作原理。我创建了这个小程序,其中子进程向父进程发送消息。大多数时候,它都有效,但有时我会收到错误消息: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;
}
谢谢。
http://pubs.opengroup.org/onlinepubs/7908799/xsh/msgrcv.html
The argument msgflg specifies the action to be taken if a message of the desired type is not on the queue. These are as follows:
- If (msgflg & IPC_NOWAIT) is non-zero, the calling thread will return immediately with a return value of -1 and errno set to [ENOMSG] ...
您正在指定 IPC_NOWAIT
,这意味着您没有给子进程足够的时间来生成任何消息。如果您从参数 msgflg
中删除它,即
if(msgrcv(qid, (void*)&recieve, 100, 1, 0) < 0)
父进程将阻塞,直到队列中有可用的东西。