c - 来自 fork() 的 pid 永远不会传给 parent ,唯一的 child

标签 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

关于为什么它不去 else/parent 点有什么想法吗?

谢谢!

最佳答案

会不会是因为stdio被缓冲了?尝试在 printfing 子 ID 后刷新输出。或者添加一个\n。或者将其fprintf发送到stderr

编辑:只是为了澄清。我的猜测并不是它没有成为父级的原因,因为它是您看不到预期输出的原因。

关于c - 来自 fork() 的 pid 永远不会传给 parent ,唯一的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12555247/

相关文章:

c - 如何解决这个深度优先搜索问题?

c - 检测新行字符

c - 如果 x>0 且 r(x) = 2x,则实现有符号到无符号映射 r(x)= 2x-1 的更快方法是什么

java - 使用 Hyperic SIGAR 获取 Java 中的系统进程列表

header 中的 C++ 整数初始化

对 BSP_LCD_Init 的调用永远不会返回。卡在 HAL_DSI_shortwrite 中

linux - 进程(任务)的 CPU 使用率 Linux 内核

java - 如何从调用同一变量的两个线程中获取相同的值?

git - 使用 Github 在 Git 中提交多个 pull 请求(一般流程)

创建新流程