3

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()?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
kanito73
  • 87
  • 4
  • The question I marked as the original does not specifically reference sockets and has a long prelude, but the question is the same ("how do I close FDs wrapped in fdopen?"), and the answer is the same (fclose closes both the `FILE*` and the underlying FD). – zneak Feb 07 '19 at 00:23

1 Answers1

2

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!

Ctx
  • 18,090
  • 24
  • 36
  • 51
  • @ScottFranco This would be a bug then. From the manpage: `The fclose() function flushes the stream pointed to by stream (writing any buffered output data using fflush(3)) and closes the underlying file descriptor.` – Ctx Oct 04 '19 at 20:22