【发布时间】: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