Hi!!
This code works if I don't remove the message queue.
In A.c I create 3 processes that send a message in a message queue.
in B.c other 3 processes receive 1 message for each (the messages sent from A), change the value of "dato" and put again the message in the queue.
The processes in A.c receive the modified message and then I should remove the queue.
The answer is: How can I remove the queue after ALL the processes have received the message? I tried with 3 wait(0) but the queue is removed after the first process has received the message and I can't understand why
Code here:
A.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/msg.h>
#define key 121121
#define max 20
typedef struct {
long type;
char data[max];
}message;
message mex;
int main(){
int i,n;
int father;
char stringaint[max];
mex.type=357;
int idqueue=msgget(key,IPC_CREAT |0600);
for(i=0;i<3;i++){
father=fork();
if(!father){
sprintf(stringaint,"%d",getpid());
strcpy(mex.dato,stringaint);
printf("The son will send the data with his PID: %s\n",mex.data);
if(msgsnd(idqueue,&mex,sizeof(message),0)==-1)
printf("It's not working!");
if(msgrcv(idqueue,&mex,sizeof(message),getpid(),0)==-1)
printf("\nMessage not received\n");
else
printf("\nMessage received");
i=3;
}
}
for (i=0; i<3; i++)
wait(0);
//Without this part the program works (but I need to remove the queue!)
msgctl(idcoda,IPC_RMID,0);
//
}
B.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/msg.h>
#define key 121121
#define max 20
typedef struct {
long type;
char data[max];
}message;
int main(){
int i;
int father;
char str[80];
messaggio temp;
int idqueue=msgget(key,IPC_CREAT |0600);
for(i=0;i<3;i++){
father=fork();
if(!father){
if(msgrcv(idqueue,&temp,sizeof(message),0,0)==-1)
printf("\nB hasn't received the message from A\n");
else
printf("\nB has received the message from A");
temp.type=atoi(temp.data);
printf("\n%d\n", temp.type);
strcat(temp.dato," ADD");
printf("%s\n",temp.data);
if(msgsnd(idqueue,&(temp),sizeof(message),0)==-1)
printf("\nNot working!!");
i=3;
}
}
}