What happens if the child does not close the socket file descriptor of the open listener by parent?

advertisements

what happens if child does not close the listener socket file descriptor opened by parent?

which process will be woken up if both are listening on master listener fd?


No process will be "woken up", you have to call accept(2). Here's what is happening.

You create a socket which makes the kernel allocate a lot of resources, a struct etc.

s = socket(....);

You set the socket in the "listening state". The kernel notices this and flips a flag or two in the struct.

listen(s, -1);

You fork(2) and now have two copies of the file descriptor. A connection arrives. Who gets it ?

Whoever calls accept first. If both are currently waiting on accept, the order cannot be determined.

When a connection arrives, the kernel adds it to a queue of "pending connections". When any process that has that file descriptor open accept(2), the kernel removes one connection from the queue and passes it to the caller (returns a new file descriptor).

As a conclusion, if the child process inherits the file descriptor it simply gets his own chance of accepting connections.