Consider a program that creates a child process printing in an infinite loop, and kills it after one second:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
int main(void) {
pid_t pid = fork();
if (pid == 0) {
while (1)
puts("I'm still alive");
} else {
sleep(1);
puts("Dispatching...");
kill(pid, SIGTERM);
puts("Dispatched!");
}
return 0;
}
The output, as I expected, was:
I'm still alive
I'm still alive
...
Dispatching...
I'm still alive
I'm still alive
...
Dispatched!
which makes sense, as the child process probably isn't instantly terminated after the father sends the singal.
However, as soon as I run the program through a pipe, or redirect the output to another file, e.g.
$ ./prog | tail -n 20
$ ./prog > out.txt
The output becomes:
I'm still alive
I'm still alive
...
Dispatching...
Dispatched!
That is, it appears to be that there's no output from the child process after the father kills it.
What is the reason for this difference?