【问题标题】:pid from fork() never goes to parent, only child来自 fork() 的 pid 永远不会去父母,只有孩子
【发布时间】:2012-09-23 18:51:18
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "structs.h"
#include "server.h"
#include "client.h"


int main(void)
{

  pid_t pid;
  int mypipe[2];
  int otherPipe[2];

  if(pipe(mypipe))
    {
      printf("Error in making a pipe");
    }
  if(pipe(otherPipe))
    {
      printf("Error creating another pipe");
    }
  if((pid=fork()) == -1)
    {
      perror("fork");
      exit(1);
    }
  printf("Child ID: %d" , pid);
  if(pid == 0)
    {
      close(mypipe[1]);
      close(otherPipe[0]);
      client *c = new client(mypipe[0], otherPipe[1]);
      wait(NULL);
      //c->startProgram();
      //return EXIT_SUCCESS;
    }
  else
    {
      printf("Yo");
    close(mypipe[0]);
    close(otherPipe[1]);
    server s;
    s.fdIn = otherPipe[0];
    s.fdOut = mypipe[1];
    s.startServer();
    //wait(NULL);
    //return EXIT_SUCCESS;
    }
}

以上是我的代码。子进程运行良好(如果我明显删除了该评论),但是 else 永远不会被执行(或者我在终端中遗漏了什么?)。

这是输出的屏幕截图:http://i.imgur.com/dUWn8.png

关于为什么它不去 else/parent 的任何想法?

谢谢!

【问题讨论】:

  • 您期待什么? strace 告诉你什么?
  • 你为什么要waiting孩子??
  • 我不知道 strace 是什么以及如何使用它。不过,当我有更多时间时,我会研究它。我实际上早先把父母和孩子换了,然后把它留在那里。认为它可能在孩子之前到达了父母。我的错。删除它并没有帮助。似乎 Michael K. 是正确的。感谢您的关注!
  • 如果您希望输出出现在屏幕上,请使用换行符结束输出,或使用fflush() 强制输出。当您的消息不以换行符结尾时,它们将保持缓冲状态,直到缓冲区溢出或添加换行符。

标签: c process fork parent


【解决方案1】:

会不会是因为stdio 被缓冲了?在printfing 子 ID 之后尝试刷新输出。或添加\n。或fprintf@stderr

编辑:只是为了澄清。我的猜测不是它没有到​​达父母的原因,因为它是你看不到预期输出的原因。

【讨论】:

  • 我同意为 printf 添加一个 \n 的想法。
  • 基本上,这三个都应该导致将其刷新到终端,所以我让 OP 来决定什么最适合他 ;-) (我也会选择 \n,因为输出然后看起来更漂亮。
  • 那行得通...你能解释一下为什么会这样吗?比如,是什么阻止了这个过程的开始,因为我在最后打印了一些没有新行的东西?
  • @JustinWarner,我正好及时编辑我的答案并添加说明;-)
  • 是的,它会将Yo 输出到内部缓冲区,但从不将其刷新到终端,因为stdout 是行缓冲的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 2016-10-03
  • 2014-03-02
相关资源
最近更新 更多