Wang Wei
Wang Wei

Reputation: 343

forked process (child) and parent process shared socket implications

I am reading on socket programming. Seems that the suggested way to implement multi-process web server is that : the parent creates a listening socket, and whenever it accepted a new connection, it will fork a child process. Since fork()-ed process inherit all the open file descriptors, the "normal" way seems to let the child close() the inherited listening socket from parent, and the let the parent side close() the newly accepted socket.

I wonder, what if the parent or the child just don't close() anything and keep using the sockets. Can two process sharing the same socket concurrently perform send/recv operations on the same shared socket? What are the implications?

Upvotes: 4

Views: 2507

Answers (2)

SergeyA
SergeyA

Reputation: 62583

Technically you can. In practice it will be impossible to write any sane code. If you try to read from the same socket in two separate application, there will be random read distribution between two (or more) processess. This design is sometimes eployed when dealing with UDP sockets, to paralellize message processing. But it is not posible to do anything in this manner with TCP sockets.

Upvotes: 5

user207421
user207421

Reputation: 310909

Can two process sharing the same socket concurrently perform send/recv operations on the same shared socket?

Yes.

What are the implications?

Possible interleaved messages, and almost certainly total chaos at the receiver.

Upvotes: 5

Related Questions