2017-05-22 5 views
-1
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <signal.h> 
#include <sys/wait.h> 
#include <unistd.h> 
#include <sys/sem.h> 
#include <sys/msg.h> 
#include <time.h> 
struct msgbuf { 
    long mtype;      /* type of message */ 
    char mtext[1000];   /* user-define message */ 
}; 

int main(){ 
    pid_t team,player; 
    int queue; 
    queue=msgget(IPC_PRIVATE,0600); 
    struct msgbuf buf1,buf2; 
    int cA,cB; 

    for(int i=0;i<1;i++){ 
     team=fork(); 
     switch(team){ 
      case -1: 
       exit(-1); 
      case 0: 

       for(int j=0;j<1;j++){ 
       player=fork(); 
       switch(player){ 
         case -1: 
          exit(-1); 
         case 0 : 
          printf("sono il figlio %d \n ",((i*5)+j)); 
          sprintf(buf1.mtext,"%d",10); 
          buf1.mtype=1; 
          cA=msgsnd(queue,&buf1,1000,0); 
          exit(0); 
        } 
       } 
       exit(0); 
       default: 
       sleep(1); 
       // flag 

     } 
    } 
    sleep(1); 
    // code 
    if(msgrcv(queue,&buf2,1000,1,0)==-1){ 
     perror("riceive "); 
    } 

    printf("%s\t%d\t%d\n",buf2.mtext,cA,cB); 
    // code 
} 

이 코드는 기본적으로 서로 다른 두 프로세스간에 comunicate를 시도합니다. msgrcnd가 msgsnd에서 msg를받지 못해서 이유를 모르겠다.이 코드는 예제 일 뿐이다. 나는 또한 플래그가 어디에 있는지 어쨌든 나는 믿지 않는 코드를 넣으려고합니다. 팁이 있습니까?msgrcv의 인수가 잘못되었습니다

답변

0

괜찮아요, 내 자신에 의해 해결, 그것은 프로세스의 동기화 및 msgsnd와 msgrcv 사이의 문제입니다, 실제로 msgrcv를 실행하는 프로세스는 msgsnd를 수행하는 프로세스 전에 실행되어야합니다.

case 0 : 
         sleep (5); // 1 modification 
         printf("sono il figlio %d \n ",((i*5)+j)); 
         sprintf(buf1.mtext,"%d",10); 
         buf1.mtype=1; 
         cA=msgsnd(queue,&buf1,1000,0); 
         exit(0); 

.

if(msgrcv(queue,&buf2,1000,1,0)==-1){ 
    perror("riceive "); 
} 
sleep(6); 2 modification 
printf("%s\t%d\t%d\n",buf2.mtext,cA,cB); 

감사합니다. msgrcv가 msgsnd보다 먼저 실행되어야합니다. 이렇게하면 두 가지 다른 프로세스간에 메시지 교환을 허용하는 올바른 실행이 보장됩니다.