Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if socket listen backlog queue is empty

Tags:

c

linux

tcp

sockets

Is there any way to check if there are no pending connection requests to the server?

In my case, I have this code, from C:

listen(mysocket, 3);
//while(no pending connections) do this
int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);

And what I need, is that while there are no pending connections, do something else, instead of getting stuck waiting, by calling accept().

like image 934
Wilhelm Sorban Avatar asked Jul 31 '26 08:07

Wilhelm Sorban


2 Answers

You can set a socket in non-blocking mode with fcntl.

fcntl(sockfd, F_SETFD, O_NONBLOCK);

After that, a call to accept(sockfd) will either immediately return a newly accepted connection or immediately fail with EWOULDBLOCK which you can use to decide to do “something else”.

Another option would be to use select, maybe with a finite timeout, to gain finer grained control over blocking.

like image 127
5gon12eder Avatar answered Aug 01 '26 23:08

5gon12eder


You can spawn a new thread and do your alternate work in that thread while the main thread waits for clients. Once a client is connected, accept() gets unblocked and then you can cancel the newly spawned thread.

The code should be on the lines of:

while(1) {
    pthread_create(&thread, NULL, do_something_else, NULL);
    consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
    pthread_cancel(thread);
}
like image 41
Arjun Sreedharan Avatar answered Aug 01 '26 21:08

Arjun Sreedharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!