Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accept4 blocks though SOCK_NONBLOCK is set

I'm trying to accept a socket non-blockingly:

accept4(s, (struct sockaddr *) &peerAddress, &len,SOCK_NONBLOCK);

where as s is a fd, peerAddres is an address, and len, is its length. I wish that accept won't block the thread. Though, once I debug, the process is stuck at this line, while no connection is pending. What is my mistake?

like image 631
Mr P Avatar asked Sep 11 '25 00:09

Mr P


2 Answers

SOCK_NONBLOCK just sets the newly accepted socket to non-blocking. It does not make accept itself non-blocking. For this one would need to set the listen socket non-blocking before calling accept.

like image 187
Steffen Ullrich Avatar answered Sep 13 '25 13:09

Steffen Ullrich


As an addition to the above answer.

Lets have a look at

accept4(s, ...);  

we want accept4() to be non-blocking.
It depedends on property of descriptor inside the function.

If descriptor s is blocking, then accept4() will be blocking.
If descriptor s is non-blocking, then accept4() will be non-blocking.

s is the descriptor of listening socket. To make s as non-blocking descriptor (according to man 2 socket):

s = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
like image 29
Alex Avatar answered Sep 13 '25 14:09

Alex