如何解决重定向到文件时 Linux 输出会发生变化
当我在终端中编译并运行下面的代码时,我得到了想要的结果
(只有一个 Parent -- pid = %d\n
行,总共创建了 15 个孩子)
但是当我将它重定向到一个单独的文件时,(例如 ./result > result.txt
)
我收到多行 Parent -- pid = %d\n
行,我希望它只出现一次。
此外,似乎创造了更多的孩子
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int level = 0; // depth of the process tree
pid_t pid;
printf("Parent -- pid = %d\n",getpid()); // expected to run only once - in the top parent process
for (int i = 0; i < 4; i++)
{
pid = fork();
if (pid == 0)
{
level++;
printf("Child - %d - Level %d\n",getpid(),level);
}
else
wait(NULL);
}
printf("End - %d\n",getpid());
return 0;
}
管道给出与重定向相同的奇怪结果:
./result | grep "Parent" | wc -l
./result | grep "Child" | wc -l
给出 16,32
我是否缺少重定向/管道的某些内容?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。