来自fork()的pid永远不会传递给父对象,而是唯一的子对象 #包括 #包括 #包括 #包括 #包括 #包括“structs.h” #包括“server.h” #包括“client.h” 内部主(空) { pid_t pid; int mypipe[2]; int-otherPipe[2]; 如果(管道(mypipe)) { printf(“制作管道的错误”); } if(管道(其他管道)) { printf(“创建其他管道时出错”); } 如果((pid=fork())=-1) { 佩罗尔(“福克”); 出口(1); } printf(“子ID:%d”,pid); 如果(pid==0) { 关闭(mypipe[1]); 关闭(其他管道[0]); client*c=新客户端(mypipe[0],otherPipe[1]); 等待(空); //c->startProgram(); //返回退出成功; } 其他的 { printf(“Yo”); 关闭(mypipe[0]); 关闭(其他管道[1]); 服务器; s、 fdIn=其他管道[0]; s、 fdOut=mypipe[1]; s、 startServer(); //等待(空); //返回退出成功; } }
上面是我的代码。子进程运行良好(如果我明显删除了该注释),但是else永远不会执行(或者我在终端中遗漏了什么?) 以下是输出的屏幕截图: 你知道为什么它不去其他/家长的地方吗来自fork()的pid永远不会传递给父对象,而是唯一的子对象 #包括 #包括 #包括 #包括 #包括 #包括“structs.h” #包括“server.h” #包括“client.h” 内部主(空) { pid_t pid; int mypipe[2]; int-otherPipe[2]; 如果(管道(mypipe)) { printf(“制作管道的错误”); } if(管道(其他管道)) { printf(“创建其他管道时出错”); } 如果((pid=fork())=-1) { 佩罗尔(“福克”); 出口(1); } printf(“子ID:%d”,pid); 如果(pid==0) { 关闭(mypipe[1]); 关闭(其他管道[0]); client*c=新客户端(mypipe[0],otherPipe[1]); 等待(空); //c->startProgram(); //返回退出成功; } 其他的 { printf(“Yo”); 关闭(mypipe[0]); 关闭(其他管道[1]); 服务器; s、 fdIn=其他管道[0]; s、 fdOut=mypipe[1]; s、 startServer(); //等待(空); //返回退出成功; } },c,process,fork,parent,C,Process,Fork,Parent,上面是我的代码。子进程运行良好(如果我明显删除了该注释),但是else永远不会执行(或者我在终端中遗漏了什么?) 以下是输出的屏幕截图: 你知道为什么它不去其他/家长的地方吗 谢谢 可能是因为stdio被缓冲了吗?尝试在printf初始化子id后刷新输出。或添加\n。或fprintf将其插入stderr 编辑:只是澄清一下。我的猜测不是因为它没有到达父级,而是因为它,这就是为什么您没有看到您期望的输出。您期望什么?strace告诉你什么?你为什么在孩子身上等待?我不知道strace是什么,怎么用
谢谢 可能是因为
stdio
被缓冲了吗?尝试在printf
初始化子id后刷新输出。或添加\n
。或fprintf
将其插入stderr
编辑:只是澄清一下。我的猜测不是因为它没有到达父级,而是因为它,这就是为什么您没有看到您期望的输出。您期望什么?
strace
告诉你什么?你为什么在孩子身上等待?我不知道strace是什么,怎么用。不过,我有更多时间的时候会去看的。事实上,我早些时候就把父母和孩子换了,然后就放在那里了。我想它可能在孩子出生之前就传到了父母那里。我的错。但是,移除它并没有帮助。看来迈克尔·K.是对的。谢谢你的关注!如果希望输出显示在屏幕上,请使用换行符结束输出,或使用fflush()
强制输出。当您的消息没有换行符结尾时,它们将一直处于缓冲状态,直到缓冲区溢出或添加换行符。我同意为printf添加一个\n的想法。基本上,这三个选项都会导致将其刷新到终端,因此我将由OP决定最适合他的选项;-)(我也会选择\n
,因为输出看起来更漂亮。这是可行的…你能解释一下为什么会这样吗?比如,是什么阻止了这个过程的开始,因为我在最后打印了一些东西,但没有新的行?@JustinWarner,我刚好及时编辑了我的答案并添加了澄清;-)是的,它会将Yo
输出到内部缓冲区,但决不会将其刷新到终端,因为stdout
是行缓冲的。
#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;
}
}