Subject: possible libc bug...
To: None <current-users@netbsd.org>
From: John Franklin <franklin@elfie.org>
List: current-users
Date: 04/05/2004 10:47:23
IMHO, this is a bug.  However, I see it happen on Linux and NetBSD.  I
have a sneaking suspicion that it'll happen on other *NIX boxes as well.

Question: What should be the output of the following program?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    printf("This will be buffered\n");
    printf("This will also be buffered.");
    fork();
    return 0;
}

I would expect: 
[1]% ./fbt
This will be buffered
This will also be buffered[2]%

Run normally, the output is actually:
[1]% ./fbt
This will be buffered
This will also be buffered.This will also be buffered.[2]%

Redirected through a pipe or by the shell to a file, the output is:
[1]% ./fbt | tee
This will be buffered
This will also be buffered.This will be buffered
This will also be buffered.[2]%

What's happening here is the printf output is being buffered by libc
before the fork().  When fork() is called, both processes have one or
both of the printf()'s buffered (depending on buffering mode, line vs
full) and the data gets flushed when the program exits and the stdout
stream is implicitly closed.

What I think should happen is the fork(2) wrapper function in libc
should call fflush(NULL) before the fork system call.

If this isn't a bug, why is it not a bug?  That is, what is it about the
semantics of printf() and fork() that make it the way it is?

Thanks,
jf
-- 
John Franklin
franklin@elfie.org
ICBM: N37 12'54", W80 27'14" Z+2100'