When I compile and run below code in the terminal, I get the desired result
(Only single Parent -- pid = %d\n
line, total 15 Children created)
But when I redirect it to a separate file, (e.g. ./result > result.txt
)
I get multiple Parent -- pid = %d\n
lines, where I expected it to appear only once.
Also, much more children seems to have been created
#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;
}
Pipeline gives same weird result as redirection:
./result | grep "Parent" | wc -l
./result | grep "Child" | wc -l
gives 16, 32
Am I missing something with redirection/pipeline?