Given the following program, named "hello" (code is below), when doing: ./hello output is:
Hello
Hello
Hello
Hello
Hello
Hello
Hello
And when executing it like that: ./hello > out.txt out.txt contains 12 Hello. Why? I understand that I redirected stdout, so Fludh might be affetcted.
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
// printf("Main PID: %d\n", getpid());
for (int j = 0; j<3; j++)
{
int pid = fork();
if (!pid)
{
printf("Hello\n");
}
}
while(wait(NULL) > 0) ;
}
In order to check the pid and ppid I changes printf("Hello\n");
with:
printf("%d PID: %d, PPID: %d\n",j, getpid(), getppid());
and got weird output on the out.txt file:
0 PID: 4432, PPID: 4431
1 PID: 4433, PPID: 4432
2 PID: 4434, PPID: 4433
0 PID: 4432, PPID: 4431
1 PID: 4433, PPID: 4432
1 PID: 4435, PPID: 4431
2 PID: 4436, PPID: 4435
0 PID: 4432, PPID: 4431
2 PID: 4437, PPID: 4432
1 PID: 4435, PPID: 4431
0 PID: 4432, PPID: 4431
2 PID: 4438, PPID: 4431
Also, When I added printf("Main PID: %d\n", getpid());
outside the loop (above it)
The out.txt contained it 8 times!
any ideas?
I was expecting the output to contains the same amount of hellos