Moritz Schmidt
Moritz Schmidt

Reputation: 2813

Should a broken socket be closed?

I am reading out of a TCP-socket:

int read_result = recv(socket_fd, &some_struct, some_size, 0);

If read_result would be equal to -1, should I still call close on that file descriptor or just leave it?

Upvotes: 0

Views: 263

Answers (1)

learnlearnlearn
learnlearnlearn

Reputation: 998

According to the recv man page there are a host of reasons for which recv might return -1(EAGAIN, EBADF, EINVAL, ENOMEM etc). I would suggest checking errno against these expected return values and modifying your code to act accordingly. If you are writing a library, you might want to return an library specific error code. If you are application, you might want to perhaps die or return an error code to the caller. It would depend on the context.

The first step to solving this however, would be to understand the various error codes that can be returned and handle them accordingly.

Upvotes: 3

Related Questions