Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 517
Wang Wei Avatar asked Sep 02 '25 05:09

Wang Wei


2 Answers

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.

like image 162
user207421 Avatar answered Sep 04 '25 19:09

user207421


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.

like image 37
SergeyA Avatar answered Sep 04 '25 21:09

SergeyA