As far as I understand, if you create a socket on POSIX-related systems, then spawn a child which inherits that socket fd, apparently you should call close
on that fd in each process when that process is done with it, as the fd is internally reference counted, and I suppose that reference count is incremented on fork
, and close
then decrements it again.
Is this the same with Windows, should you call closesocket
in each process that has a copy of that socket, or do you only call it in one process, when all processes are done with it?
Edit: the question marked as a duplicate of this one is relevant (Are TCP SOCKET handles inheritable?), as it suggests that inheriting SOCKETs is error-prone, but it also suggests that it's still possible. In which case, if one persists regardless of the possible errors, then it would be good if this question had an answer; should one closesocket
in all processes, or just the parent?
Second edit: I believe this question is answered in the documentation for WSADuplicateSocketA
:
A process can call closesocket on a duplicated socket and the descriptor will become deallocated. The underlying socket, however, will remain open until closesocket is called by the last remaining descriptor.