Invalid argument on msgrcv in c

521 views Asked by At
#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
}

this code basically try to comunicate between two different process . who can help me , because the msgrcv don't receive the msg from the msgsnd and I don't understand why .this code is only a sample. i also try tu put the code where is the flag but anyway I doesn't what I believe . any tips ?

1

There are 1 answers

0
duca On

ok , i solved by my self , it is a problem of synchronization of the process and between the msgsnd and msgrcv , in fact the process that execute the msgrcv must be executed before the process that do the 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);

thanks the 2 modifications the msgrcv must run before thee msgsnd . This guarantees the correct running that permit the exchange of message between 2 different process.