0
votes

I want to write a multi clients socket program,
but I get Bad file descriptor when the stage of accept.
How can I correct my code? Thanks!

Here is my code
http://codepad.org/q0N1jTgz
Thanks!
Here is my part of code!

while(1)
{
    struct sockaddr_in client_addr;
    int addrlen = sizeof(client_addr);

    /*Accept*/
    if(clientfd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t*)&addrlen) < 0)
    {
        perror("Accpet Error");
        close(sockfd);
        exit(-1);
    }

    /*Fork process*/
    if(child = fork() < 0)
    {
        perror("Fork Error");
        close(sockfd);
        exit(-1);
    }
    else if(child == 0)
    {
        int my_client = clientfd;
        close(sockfd);

        send(my_client, welcome, sizeof(welcome), 0);

        while ((res = recv(my_client, buffer1, sizeof(buffer1), 0)) > 0)
        {
            string command(buffer1);
            cout << "receive from client:" << command << ", " << res << " bytes\n";
            memset(buffer1, '\0', sizeof(buffer1));     
        }
    }

    close(clientfd);

} 
1
Please include the relevant parts of your code in your question by editing it. The codepad will go away any time. - user647772

1 Answers

2
votes

there are a few bugs in your code first you need to use parentheses around the assignments for child and clientfd.

line 68 should be changed to

 if((clientfd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t*)&addrlen)) < 0)

and line 76 should be

  if((child = fork()) < 0)

additionally you must return or exit() from the forked process since you have already closed the listening socket.

so add exit(0); or return 0; after line 94

I highly recommend you compile your code with warnings enabled, to catch the assignment problems early. e.g use the -Wall and -Wextra flags if you are using gcc or g++