#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
}
这段代码基本上试图在两个不同的进程之间进行通信。 谁可以帮助我,因为msgrcv没有从msgsnd收到消息,我不明白为什么。这个代码只是一个样本。 我也尝试把代码放在哪里是旗帜,但无论如何我不是我相信的。 有小费吗 ?
答案 0 :(得分:0)
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之前运行的两次修改。 这保证了正确的运行,允许在两个不同的进程之间交换消息。