Skip to content
Advertisement

Linux Socket Bad File Descriptor

I couldn’t find a duplicate, so I decided to post. We’re getting into Sockets (beginner-level) now, and was given the code below to make the client send a simple message to the server by using send() and recv(). However, everything I have tried doesn’t seem to get rid of the error: Bad File Descriptor and newsockfd always returns the value -1. I’m confused and have no idea why it doesn’t work.

defs.h

JavaScript

client.c

JavaScript

server.c

JavaScript

Thanks for your time.

Advertisement

Answer

In the code of the child you close sockfd, which represents the server. But in the next iteration of the infinite for-loop, which the child also runs, you attempt to accept() a new client using sockfd. Therefore, sockfd is a Bad file descriptor.

Remove the close(sockfd); line in your code and close it when you can be absolutely sure it is not needed anymore.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement