我有一个简单的 ipc 程序。服务器生成一个随机数,并从标准输入读取多个客户端。每个客户端向服务器发送随机数,直到他们猜出服务器的号码。当超过 n/2 个客户端猜到这个数字时,服务器停止。我的问题是服务器在第一个客户端猜到数字后停止。
服务器代码:
int i=0; // the number of clients who guessed the number
srand(getpid());
numarul = rand() % 20;
printf("Numarul generat este %d \n",numarul);
for(;;){
if(msgrcv(coadaId,&mesg,sizeof(Mesaj),1,0)<0) // read the mesage from queue
printf("Eroare la receptionarea mesajului.");
else{
printf("Am primit numarul %d \n", mesg.nr);
if(mesg.nr == numarul){
i++; // is the number is guessed
printf("S-a ghicit numarul de la %d clienti \n",i);
mesg.val=1;} // msg.val = 1 if number is guessed
mesg.tip=2; // change the message type
msgsnd(coadaId,&mesg,sizeof(Mesaj),0); // send the msg.val . if 1 client stops
mesg.val=0;
if(i>n/2)break; // the loop ends when i is bigger than half number of clients
}
}
客户端代码:
mesg1.val=0;
srand(getpid());
while(mesg1.val!=1){
mesg1.nr = rand() % 20; // generates number
mesg1.tip=1; // type = 1
if(msgsnd(coadaId,&mesg1,sizeof(Mesaj),0)<0) // sends message to queue
printf("Eroare la trimiterea mesajului:");
msgrcv(coadaId,&mesg1,sizeof(Mesaj),2,0); // reads message from the server
if(mesg1.val==1)exit(0); // if the number is guessed quit
}
谢谢