gpt4 book ai didi

c - fork 子 "prints"重定向标准输出两次

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:16 24 4
gpt4 key购买 nike

一段时间内(1)我正在尝试:

  • 使用 fork() 生成一个子进程;

  • 重定向子进程标准输出以便父进程可以看到它

  • 在终端打印父进程的结果

  • 重复

奇怪的是,子进程的输出好像打印了两次

// 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("before\n");
printf("parent tried to read something from its child and got: %s\n", respBuffer);
printf("after\n");
} 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() 之前刷新标准输出缓冲区似乎无法解决问题

有趣的是,删除 while 循环并保持其他一切完好无损似乎工作正常

最佳答案

在循环的第一次迭代中,您关闭了父级中的 childToParent[1],并且您没有重新创建管道,因此在循环的第二次迭代中,它试图重用那些关闭的管道,所以 child 的 dup2 调用失败,所以它的 printf 转到终端。同时,在父级中,read 调用返回 0 而不向缓冲区写入任何内容,因此您只需打印旧内容。

关于c - fork 子 "prints"重定向标准输出两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com