#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
被缓冲了?尝试在 printf
ing 子 ID 后刷新输出。或者添加一个\n
。或者将其fprintf
发送到stderr
。
编辑:只是为了澄清。我的猜测并不是它没有成为父级的原因,因为它是您看不到预期输出的原因。
关于c - 来自 fork() 的 pid 永远不会传给 parent ,唯一的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12555247/