Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't accept() block?

Tags:

c

linux

tcp

sockets

I'm new in socket programming under Linux (UNIX) sockets. I found the following code in the Internet, for a tcp-server that spawns a thread for each connection. However it doesn't work. the accept() function returns instantly, and doesn't wait for connection. What am I doing wrong ?

this is the code

int main(int argv, char *args[])
{
    struct sockaddr_in addr;
    int sd, port;

    port = htons(SERVER_PORT);

    /*--- create socket ---*/
    sd = socket(PF_INET, SOCK_STREAM, 0);
    if ( sd < 0 )
        panic("socket");

    /*--- bind port/address to socket ---*/
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = port;
    addr.sin_addr.s_addr = INADDR_ANY;                   /* any interface */
    if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
        panic("bind");

    /*--- make into listener with 10 slots ---*/
    if ( listen(sd, 10) != 0 )
        panic("listen")

    /*--- begin waiting for connections ---*/
    else
    {   int sd;
        pthread_t child;
        FILE *fp;

        while (1)                         /* process all incoming clients */
        {
            sd = accept(sd, 0, 0);     /* accept connection */
            fp = fdopen(sd, "wr+");           /* convert into FILE* */
            pthread_create(&child, 0, servlet, fp);       /* start thread */
            pthread_detach(child);                      /* don't track it */
        }
    }
} 
like image 962
stdcall Avatar asked Jan 15 '23 13:01

stdcall


2 Answers

You are shadowing the sd variable, passing an invalid socket to accept() which causes it to fail immediately.

It will likely return EBADF to signal a bad file descriptor. You would have noticed if you checked the return value in your code.

You should enable more compiler warnings, to catch things like these. With GCC you can use the -Wshadow option to enable such a warning.

like image 151
unwind Avatar answered Jan 21 '23 09:01

unwind


You're not checking the return value of accept() call. Most likely it's returning an error.

like image 38
m0skit0 Avatar answered Jan 21 '23 11:01

m0skit0