2017-01-28 8 views
1

メッセージキューの仕組みを理解しようとしています。子プロセスが親プロセスにメッセージを送るこの小さなプログラムを作成しました。ほとんどの場合、動作しますが、時々私はエラー: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; 
} 

ありがとう。

答えて

1

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) 

から親プロセスがブロックされることをドロップした場合。

関連する問題