I am working on a server application in C using Pthreads(Linux).Everything works fine, clients can connect with the server and transfer data. The problem being faced is that my software keeps stuck at accept till it does not receive a new request from a client.
Here is my code:
while((connfd = accept(sock_desc, (struct sockaddr *)&echoClntAddr (socklen_t*)&clntSock)))
{
puts("Connection accepted");
if( pthread_create( &thr, NULL , connection_handler , (void*) &connfd) < 0)
{
perror("could not create thread");
return 1;
}
puts("Handler assigned");
}
I am able to run multiple threads but my main thread gets stuck at the accept
function. How can I solve this problem so that I can do other work in the main thread while my other threads are running?
As I mentioned in the comments,
accept
is a blocking call unless you specify the socket to be nonblocking.You can achieve this with the following:
You can do error checking with the return value from
fcntl