Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...