try this:
void exit_message (void)
{
// use write to have an unbuffered output
char m[100];
sprintf (m, "%d exit\n", getpid());
write (1, m, strlen(m));
}
main(){
atexit (exit_message);
printf("%d test 1\n",getpid());
fork();
printf("%d test 2\n",getpid());
}
The output will look like this:
14866 exit // <- parent process flushes its output at exit
14866 test 1 // <- parent process: 1st printf
14866 test 2 // <- parent process: 2nd printf
14867 exit // <- forked process flushes its output at exit
14866 test 1 // <- forked process: unflushed parent process output buffer
14867 test 2 // <- forked process: 2nd printf
we can see the only printf done by the forked process is the last one, as expected.
The previous line is a ghost of the stdout output buffer, which has been duplicated by fork() before being flushed.
Making stdout unbuffered
main(){
atexit (exit_message);
setvbuf(stdout, NULL, _IONBF, 0);
printf("%d test 1\n",getpid());
fork();
printf("%d test 2\n",getpid());
}
gets rid of the ghost
14866 test 1 // <- parent process: 1st printf
14866 test 2 // <- parent process: 2nd printf
14866 exit // <- parent process exits
14867 test 2 // <- forked process: 2nd printf
14867 exit // <- forked process exits