Home > Back-end >  What is the difference between epoll and multiple connect attempt?
What is the difference between epoll and multiple connect attempt?

Time:07-30

Let's say i have a non blocking TCP client socket. I want to connect to a TCP server. I found that either of the following ways can be used to do so.

int num_of_retry=5;
for(int i=0;i<num_of_retry;i  ){
   connect(SOCKET_FD,...);
   sleep(1000ms);
}

and this

connect(SOCKET_FD,...);
epoll_wait(...,5000ms)

What are the main difference in the above two approaches, performance and otherwise?

CodePudding user response:

In this particular example, the main difference is that sleep() will not exit until the full interval has elapsed, whereas epoll() (and select(), too) will exit sooner if the pending connect operation finishes before the full interval has elapsed.

Otherwise, both examples are blocking the calling thread until something happens (which kind of defeats the purpose of using a non-blocking socket - except that this approach is the only way to implement a timeout with connect()).

Note that in either example, if you call connect() on a socket while it is already working on connecting, connect() will fail with an EALREADY error. If a connect operation times out, you should close() the socket and create a new socket before calling connect() again. And you should wait for epoll() (or select()) to tell you when the operation is finished, don't just call connect() in a loop until it reports something other than EALREADY.

  • Related