一个客户端停止后,Unix ipc服务器停止

时间:2012-05-31 19:15:55

标签: c queue ipc

我有一个简单的ipc程序。服务器生成一个随机数,并从stdin中读取多个客户端。每个客户端向服务器发送随机数,直到他们猜出服务器的号码。当超过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 
  }

由于

2 个答案:

答案 0 :(得分:0)

尽管算术运算符优先于相等运算符,但使用括号来提高清晰度仍然是一个好主意。

答案 1 :(得分:0)

i等于0,并且在第一个客户端猜测数字后等于1。服务器循环在i>n/2时结束。如你所说,当i等于1时会发生这种情况。由此得出0≤n/ 2 <1。 1⇔0≤n&lt;1≤0 2,所以,如果n是整数,则为0或1.如果您不相信,请在循环后显示n