How to close a socket() if I used fdopen() on the socket descriptor

1k Views Asked by At

If I create a socket

sockfd = socket(...);

and then I associate it to a FILE stream by calling

FILE* f=fdopen(sockfd,"r+");

Should I call both close(sockfd); and fclose(f); or only close(sockfd);? What happens to the FILE structure if I call or not fclose(f)?

And (the most important), if I should call both of them, in which order they must be called? First close() or fclose()?

1

There are 1 best solutions below

1
On

fdopen() wraps the file descriptor into a buffered io FILE structure, just as you had opened it with fopen().

You should only call fclose(), this will both close the os file descriptor and free all associated structures and buffers!