jon
jon

Reputation: 21

in socket programming, can accept() the same listening socket in multi-process(thread)?

i.e.

  1. open a listening socket in parent process
  2. call epoll_wait(listening_socket) in child1,child2,child3....
  3. call accept in each child if there is connection request

Upvotes: 2

Views: 3990

Answers (2)

Horacio
Horacio

Reputation: 2765

Yes you can but your example is a little incomplete:

  1. Create listening_socket
  2. Create epoll set using epoll_create
  3. Register listening_socket to the epoll set using epoll_ctl
  4. call epoll_wait(epoll set) in child1,child2,child3....
  5. call accept in each child if there is connection request

epoll_wait makes sures that only one thread gets the connection event and only that thread will call accept.

If you create two epoll sets and register your listening_socket to both of them you will receive the event twice, once per epoll set, and this is not recommended.

You may refer to this tutorial http://www.devshed.com/c/a/BrainDump/Linux-Files-and-the-Event-Poll-Interface/ and search some interesting discussions about epoll in this forum http://www.developerweb.net/forum/ to learn more.

For more elaborate examples you can always refer to the libev, libevent or nginx source code.

Upvotes: 4

David Gelhar
David Gelhar

Reputation: 27900

In general, it's not a good idea to have multiple threads performing IO on the same socket without some kind of synchronization between them. In your scenario, it's possible you'd see something like:

  • incoming connection request wakes up epoll_wait in all N child threads
  • all N threads call accept, 1 call succeeds, N-1 block (or fail, if your listening socket is non-blocking)

The more usual approach is to have the parent thread loop calling accept on the listening socket, and starting a child thread for each incoming request. (Or, if you're concerned about thread creation overhead, you can have a pool of child threads that wait on a condition variable when idle; the parent adds the newly-accepted socket to a queue and uses pthread_cond_signal to wake a child to handle it.)

Upvotes: 5

Related Questions