"乒乓球"使用unix进程和管道进行游戏

时间:2015-04-27 07:08:25

标签: c unix process pipe

有人可以帮我解决这个问题吗?

我在下面写了完整的问题。

乒乓。两个进程将发挥乒乓球比赛。 第一个进程将生成一个介于5000和15000之间的随机数,该数字将发送到另一个进程。 此过程将减去一个随机值(介于50和1000之间)并将数字发回, 进程之间的聊天将使用管道通道实现。 当值低于零时,游戏结束。 每个进程都将打印收到的值。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

int main ()
{

  int  p2c[2], c2p[2], number, n;

  pipe(p2c);    //parent to child pipe
  pipe(c2p);    //child to parent pipe

  number = rand() %10000 + 5000;
  printf("Generated number: %d\n", number);

  if (fork () == 0 ) 
  { //child process
      while(number > 0)
      {
         printf("in child process\n");
         read(p2c[0], &number, sizeof(int));
         printf("(F).received number: %d\n", number);
         n = rand() %1000 + 50;
         number = number - n;
         write(c2p[1], &number, sizeof(int));
       } 
      close(p2c[0]); close(p2c[1]);
      close(c2p[0]); close(c2p[1]);
      exit(0);

  } else {
    while(number > 0) 
    {
      printf("in parent process\n");
      read(c2p[0], &number, sizeof(int));
      printf("(P).received number: %d\n", number);
      number = number - n;
      write(p2c[1], &number, sizeof(int));
    }
   close(p2c[0]); close(p2c[1]);
   close(c2p[0]); close(c2p[1]);
   wait();
 }
printf ("The final number is: %d\n", number);
}

它不起作用,我不明白为什么。所有它打印的是:

Generated number: (a random number...)
in parent process
in child process

另外,我不明白为什么它首先进入父进程而不进入子进程。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

首先,没有命令fork ed进程。尽管子代码的源代码高于父代,但子代和父代同时执行或多或少。在这里,父母碰巧在标准输出上拍了一下比孩子快一点。

您遇到的主要问题是死锁。父母正在等孩子说些什么(read(c2p[0]...));孩子正在等待父母打破沉默(read(p2c[0], ...))。其中一个人必须先说些什么,否则他们会在搬家之前就死了。

通过告诉对方初始状态,让他们中的一个在循环之前说话。然后它应该可以在以后工作,因为它们在说话和聆听之间交替。

相关问题