tags:

views:

50

answers:

1

I'd like to make sure about the correctness of the way I try to use accept() on a socket.

I know that in Linux it's safe to listen() on a socket, fork() N children and then recv() the packets in all of them without any synchronisation from the user side (the packets get more or less load-balanced between the children). But that's UDP.

Does the same property hold for TCP and listen(), fork(), accept()? Can I just assume that it's ok to accept on a shared socket created by the parent, even when other children do the same? Is POSIX, BSD sockets or any other standard defining it somewhere?

+1  A: 

If you fork() and then accept() in your children only one child process is going to call accept() on a connection and then process it. This is pre-forking and the connections won't be shared among the children.

You can do a standard one child per connection scheme by reversing the order and accepting and forking. However both of these techniques are for efficiency, balancing, etc., not for sharing a particular connection.

TCP is different from UDP. It would be inadvisable to do that in TCP as you will almost certainly end up with a mess. A given received message can be spread over one or more packets and it would be more of a pain for multiple process to coordinate than would be to have one child handle the connection.

Duck
The first paragraph of your answer is what I was interested in really. Can I accept() (on the parent socket) in each child safely without any locking? Or more precisely, run a `while(1) {accept(); process(); close();}` loop in each child?
viraptor
@viraptor: Yes, you can.
caf
@viraptor - Yes, exactly that, leaving a way out of loop other than killing the process.
Duck