When I create a socket using accept() and make a FILE out of it using fdopen(), what do I have to do to clean everything up? Do I need to do fclose() on the FILE, shutdown() and close() on the socket, or only the shutdown() and or close() or fclose()? If I don't do fclose(), do I have to free() the FILE pointer manually?
Yes, it's a good idea to close file descriptors as soon as you no longer need them if only to release the associated resources and avoid reaching limits. Now, some file descriptors may be open through some APIs, and you should use that same API to close them (not use the close(2) system call).
If fdopen() returns NULL, use close() to close the file. If fdopen() is successful, you must use fclose() to close the stream and file.
close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).
A socket is just a special form of a file. For example, you can use the syscalls used on file descriptors, read() and write(), on socket descriptors.
From man fdopen:
The file descriptor is not dup’ed, and will be closed when the stream created by fdopen() is closed
So I would just use fclose(), which also closes the underlying file descriptor. I don't know whether shutdown() is needed, either.
From http://opengroup.org/onlinepubs/007908775/xsh/fclose.html
The fclose() function will perform a close() on the file descriptor that is associated with the stream pointed to by stream.
If you've wrapped your socket in a stream it probably no longer makes sense to shutdown(), at least not without flushing the stream first. But I won't swear to that, because I don't know that there are no uses where you'd want to shutdown() rather than just close().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With