开发者

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

开发者 https://www.devze.com 2023-03-21 18:30 出处:网络
what happens if child does not close the listener开发者_如何学C socket file descriptor opened by parent?

what happens if child does not close the listener开发者_如何学C 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.


Several processes can accept() on the same socket. When a connection arrives, depending on the OS, the OS may wake up one process or all the processes (thundering herd), but in any case, only one process will succeed in accept()ing the new connection.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号