Server program gets stuck at accept function

3.7k views Asked by At

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?

2

There are 2 answers

2
Alejandro On BEST ANSWER

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:

fcntl(sock_desc, F_SETFL, fcntl(sock_desc, F_GETFL, 0) | O_NONBLOCK);` 

You can do error checking with the return value from fcntl

0
Werner Henze On

There are two ways to achieve what you want.

  1. You can set the socket to nonblocking. In that case accept will return immediately.
  2. You can use select (or poll) to wait until the socket is ready to accept or a timeout occurs. If you put that into your main loop you can check after select if it returned because an incoming connection is waiting (and accept it) or if the timeout occurred (and you do your other stuff).