This is the mail archive of the cygwin mailing list for the Cygwin project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: fork() + file descriptor bug in 1.7.27(0.271/5/3) 2013-12-09 11:54


On 01/14/2014 08:50 AM, tednolan@bellsouth.net wrote:
> In message <52D55D96.8070407@redhat.com>you write:
>>
>> Your program may be violating POSIX, which would trigger undefined behavior.
>>
>> Quoting POSIX:
>> pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_05
>>
> 
> [long quote elided]
> 
> Yikes!  That's pretty impenatrable.  And if it says what I think it says,
> it seems to violate the way I've understood Unix fork() and how fds 
> (and stdio buffers) are inherited since forever.

It says that, intuitively,

putc('a');
fork();
exit();

may or may not print 'a' twice, because both parent and child are
operating on the same stream buffer when they call exit() (which implies
a fflush()).  The fix is to:

putc('a');
fflush(NULL);
fork();
exit();

and now you are guaranteed 'a' is only printed once.

You have the same problem, but in the read direction.  You have both
parent and child with a stream buffer that hasn't yet been flushed back
to the fd underlying the stream.  If you add an fflush(NULL) before the
fork(), your bug should go away (if it doesn't, then _that's_ a cygwin
bug).  Yes, it's annoying that BSD and glibc don't comply with POSIX
behavior, and thereby mask the effects of your bug.  And we are patching
cygwin to mirror glibc's bug, so that your bug will also be masked on
cygwin.  But that's no excuse to not fix your program to not trigger the
bug in the first place.

> 
> However..
> 
> Do I understand that to say that if the first thing my child does is
> 
> 	fclose(fp);
> 
> everything should be hunky-dory?

No.  You have to fix things _in the parent, before the fork()_ for
everything to be hunky-dory.  The easiest way to do that is to
fflush(NULL) before fork()ing.

-- 
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]