0

Is it possible for multiple processes to listen on a same socket?

For example I have 5 clients, and one process acting as a server writes on a socket and all the 5 clients receive the same mesage.

Eko
  • 1,487
  • 1
  • 18
  • 36

1 Answers1

2

Yup it is very much possible for multiple processes listening on same port by using fork ().

In fact most of the web servers use this to enhance the performance when there is a requirement to receive message from huge number of clients.

Just create the listener & fork the processes. Now all the processes will be listening on the same port. Now how they divide the incoming requests among themselves totally depends upon the OS like in Solaris the requests are divided among the processes on round-robin basis.

But for your scenario you can use socket multiplexing (select ()) to attain the required result.

Ankit Tripathi
  • 374
  • 1
  • 8
  • Just be aware of the fact that `accept()` may fail! – Mark Nunberg Oct 19 '14 at 17:42
  • When & how accept can fail buddy..... I have used both of them a number of times. Accept never failed for me. Yup select can timeout but that is not an issue. – Ankit Tripathi Oct 19 '14 at 18:39
  • 3
    It's technically possible that the read-ready notification would arrive on both processes at the same time, but only a single socket would be `accept()`ed, letting the other one get an error code of `EAGAIN`. The comment was more intended above as a note for the OP :) – Mark Nunberg Oct 19 '14 at 19:32