Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing/cleaning up "mixed" file descriptors / sockets

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?

like image 521
jkramer Avatar asked Sep 20 '08 12:09

jkramer


People also ask

Do you have to close file descriptors?

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

How do you close a Fdopen?

If fdopen() returns NULL, use close() to close the file. If fdopen() is successful, you must use fclose() to close the stream and file.

What happens when a file descriptor is closed?

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

Is sockets available through file descriptors?

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.


2 Answers

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.

like image 168
tsg Avatar answered Oct 02 '22 08:10

tsg


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

like image 45
Steve Jessop Avatar answered Oct 02 '22 07:10

Steve Jessop