sockets and close-on-exec (F_SETFD)
Fri Apr 14 10:14:00 GMT 2000
I have some socket code that does the typical series of
socket, bind, listen, accept, connect, and close calls.
The sockets are marked for close-on-exec with
fcntl(fd, F_SETFD, 1). Unfortunately, in some circumstances,
not entirely deterministic, a bind fails with EINVAL
(which according to MSDN means the socket is already
bound to an address).
After a lot of tracing, I found that the close-on-exec flag
uses code in set_inheritance that does a CloseHandle (after
a DuplicateHandle) instead of a closesocket. In my code,
handles end up getting reused because they have been previously
closed (either with closesocket or CloseHandle). However,
bind seems to be extra-fussy and unless the reused handle
was closed with a closesocket it fails with WSAEINVAL.
I added some code so that set_inheritance can call
closesocket if a handle is a socket and my problem
goes away. Similarly, if I don't use close-on-exec
the problem goes away.
Does this make any sense?
More information about the Cygwin-developers