在一段时间内(1(我正在尝试:
-
用叉子((;
产生儿童过程 重定向子过程stdout,以便父进程可以看到它
从父进程中打印结果
重复
奇怪的是,子过程的输出似乎是两次打印的
// parentToChild and childToParent are the pipes I'm using
while(1) {
int pid = fork();
if(pid < 0) {
// error, get out
exit(0);
} else if(pid != 0) {
// parent process
close(parentToChild[0]); // don't need read end of parentToChild
close(childToParent[1]); // don't need write end of childToParent
sleep(4);
char respBuffer[400];
int respBufferLength = read(childToParent[0], respBuffer, sizeof(respBuffer));
printf("beforen");
printf("parent tried to read something from its child and got: %sn", respBuffer);
printf("aftern");
} else if (pid == 0) {
if(dup2(childToParent[1], STDOUT_FILENO) < 0) {
// printf("dup2 error");
};
close(childToParent[1]);
close(childToParent[0]);
close(parentToChild[1]); // write end of parentToChild not used
printf("child message");
// if we don't exit here, we run the risk of repeatedly creating more processes in a loop
exit(0);
}
}
我希望每次迭代时以下循环的欧普特为:
before
parent tried to read something from its child and got: child message
after
但是,在每次迭代中,我都会得到:
before
parent tried to read something from its child and got: child message
after
child message
第二张"儿童消息"背后的原因是什么?
在调用fork((之前对flush flush flush flush fork((似乎无法解决问题
有趣的是,删除时循环并保持其他所有内容似乎可以正常工作
在循环的第一次迭代中,您在父母中关闭childToParent[1]
,并且不重新创建管道,因此在循环的第二个迭代中,它试图重复使用这些关闭管道,因此孩子的dup2
呼叫失败,因此其printf进入终端。同时,在父母中, read
调用返回0而无需写任何内容,因此您只需打印旧内容。