Reputation: 1131
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().
Upvotes: 3
Views: 2892
Reputation: 25449
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.
Upvotes: 4
Reputation: 11453
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);
}
Upvotes: 1