我有一個簡單的ipc程序。服務器生成一個隨機數,並從stdin讀取一些客戶端。每個客戶端都會向服務器發送隨機數,直到他們猜到服務器的編號。當超過n/2個客戶端猜測數量時,服務器停止。我的問題是服務器在第一個客戶端猜到數字後停止。一臺客戶機停止後,Unix ipc服務器停止
服務器代碼:
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
}
感謝
在服務器代碼中,「n」是否曾經根據客戶端數量遞增? –
不,使用scanf在服務器代碼中讀取n,並保持不變 – vladCovaliov