【问题标题】:"Ping pong" game with unix processes and pipes带有 unix 进程和管道的“乒乓”游戏
【发布时间】:2015-04-27 07:08:25
【问题描述】:

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

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

乒乓球。两个进程将进行乒乓球比赛。 第一个进程将生成一个介于 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

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

【问题讨论】:

  • fork() 可以返回 3 个不同的条件 1) -1 = 失败 2) >0 = 父 3) =0 = 子。发布的代码没有处理错误情况
  • main 函数清楚地表明它将在退出时返回一个 int。所以父母需要以'return(0);'结尾大多数编译器设置都会发出有关主函数不正确退出的警告
  • 孩子在发送最后一个
  • 对已发布代码的编译会引发一些关于使用隐式等待声明的警告。这是因为发布的代码中的调用与相关头文件中的原型不匹配。所以真正发生的事情是任何人的猜测。此外,在父级中,变量“n”在使用之前未初始化。建议编译启用所有警告并修复警告,然后重新发布代码

标签: c unix process pipe


【解决方案1】:

首先,forked 进程没有顺序。尽管子代码的源代码比父代码高,但子代码和父代码或多或少同时执行。在这里,父母碰巧在标准输出上拍手比孩子快一点。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    相关资源
    最近更新 更多