1

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.

Tom
  • 61
  • 1
  • 4

1 Answers1

1

You shouldn't see sockets on Windows as file descriptors, so they don't get inherited the same way. See this link for the full answer to your question: Are TCP SOCKET handles inheritable?

Brecht Sanders
  • 6,215
  • 1
  • 16
  • 40
  • Thanks for the answer. I may have accepted a bit prematurely though; the link indicates that treating SOCKETs as inheritable is error-prone, but possible. If we do treat them as inheritable despite the problems, then I'd still be glad to see an answer to my original question; should closesocket then be called in all processes, or just the parent? – Tom Jun 10 '21 at 13:24