views:

613

answers:

3

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?

A: 

You have 2 things here you need to clean up: the stream represented by FILE and the file descriptor represented by the socket. You need to close the stream first, then the file descriptor. So, in general you will need to fclose() any FILE objects, then close() any file descriptors.

Personally I have never used shutdown() when I want to cleanup after myself, so I can't say.

edit

Others have correctly pointed out that fdclose() will also close the underlying file descriptor, and since calling close() on a close file descriptor will lead to an error, in this case you only need fdclose().

freespace
+4  A: 

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.

tsg
Very good point.
freespace
+3  A: 

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

Steve Jessop