2018年2月14日 星期三

C bad file descriptor: error on accept()

code example:
while(1) {
        ...
        newsockfd = accept(listenfd, (struct sockaddr *) &cli_addr, &clilen);
        
        if (newsockfd < 0) {
            perror("server: accept error");
            exit(1);
        }

        if ((pid = fork()) < 0) {
         perror("fork error:");
            exit(3);
        } else {
            if (pid == 0) {  
                cout<<"close listenfd in child\n";
                close(listenfd);
                handle_socket(newsockfd,cli_addr);
            } else { 
             cout<<"close newsockfd in parent\n";
                close(newsockfd);
            }
        }
}

If you don't kill child after accept function,
the program will keep forking another child process.
Then, another "children"(depends on how many times you fork) also want to accept connection in while loop.
This situation leads to accept error.

Solution:
add exit(0) to your child process

沒有留言:

張貼留言