来自fork()的pid永远不会转到父级,只有子级

时间:2012-09-23 18:51:19

标签: c process fork parent

#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

关于为什么不去其他/父母点的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:3)

可能是因为stdio被缓冲了吗?在printf子ID后尝试刷新输出。或者添加\n。或fprintf将其stderr

编辑:只是澄清一下。我的猜测并不是因为它不是父母的原因,因为这就是为什么你没有看到你期望的输出。