I am having a simple program to send numbers 0 to 2 into a pipe, then function fork_child receive number from this pipe and print out the 1st number it receive and send following number into another pipe connecting to the next child created by fork_child:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
void fork_child(int port_in, int generation) {
int number;
int receive_first_number = 0;
int pid = -1;
int fd[2];
while (read(port_in, &number, sizeof(number)) != 0) {
if (receive_first_number == 0) {
receive_first_number = 1;
printf("child-%d (pid %d) receives: %d\n", generation, getpid(), number);
continue;
}
if (pid == -1) {
// execute only once to create child
pipe(fd);
pid = fork();
if (pid == 0) {
// child process
close(fd[1]);
fork_child(fd[0], generation + 1);
close(fd[0]);
exit(0);
} else {
// parent process
close(fd[0]);
}
}
// send number to next child
write(fd[1], &number, sizeof(number));
}
close(fd[1]);
wait(&pid);
}
int main() {
int fd[2];
pipe(fd);
int pid = fork();
if (pid == 0) {
// child process
close(fd[1]);
fork_child(fd[0], 0);
close(fd[0]);
exit(0);
} else {
// parent process
close(fd[0]);
for (int number = 0; number < 3; number++) {
write(fd[1], &number, sizeof(number));
}
close(fd[1]);
wait(&pid);
}
return 0;
}
It works as expected when running:
$ ./pipe
child-0 (pid 149437) receives: 0
child-1 (pid 149438) receives: 1
child-2 (pid 149439) receives: 2
execept capturing the output and redirect into a file:
$ ./pipe > out
$ cat out
child-0 (pid 151246) receives: 0
child-1 (pid 151247) receives: 1
child-2 (pid 151248) receives: 2
child-0 (pid 151246) receives: 0
child-1 (pid 151247) receives: 1
child-0 (pid 151246) receives: 0
Why is captured output different from what it was without pipe and redirecting?