Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

linux - Why does accept() block, when listen() is the very first involved in TCP?

The accept() blocks, until another connection is made and the return the sockfd the can communicate both sides on. But why is it accept() that blocks, when the first thing that is done is the three way handshake. And the handshake is not done by accept(), but by listen(). So I would expect to listen() block rather then accept(), since it is firstly involved in TCP. I know the kernel does some queuing of the incoming connections, but still the very first function involved in is listen(), then the connection is moved forward in the queue to accept(). So when I do first connection, listen() will do the 3whs, and the server blocks in accpet(). So another connection cannot do another 3whs, becuase the server does no go back to listen(), which does the 3whs? Or why does accept() blocks and not listen()?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

listen() and accept() are two completely different operations. Yourr understanding of how they work is incorrect.

listen() merely sets up the listening socket's backlog and opens the bound port, so clients can start connecting to the socket. That opening is a very quick operation, there is no need to worry about it blocking.

A 3-way handshake is not performed by listen(). It is performed by the kernel when a client tries to connect to the opened port and gets placed into the listening socket's backlog. Each new client connection performs its own 3-way handshake.

Once a client connection is fully handshaked, that connection is made available for accept() to extract it from the backlog. accept() blocks (or, if you use a non-blocking listening socket, accept() succeeds) only when a new client connection is available for subsequent communication.

You call listen() only 1 time, to open the listening port, that is all it does. Then you have to call accept() for each client that you want to communicate with. That is why accept() blocks and listen() does not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...