views:

902

answers:

4

Of course, the immediate answer for most situations is "yes", and I am a firm believer that a process should correctly cleanup any resources it has allocated, but what I have in my situation is a long-running system daemon that opens a fixed number of file descriptors at the startup, and closes them all before exiting.

This is an embedded platform, and I'm trying to make the code as compact as possible, while not introducing any bad style. But since file descriptors are closed before exit anyway, does this file descriptor cleanup code serve any purpose? Do you always close all your file descriptors?

+1  A: 

man 3 exit:

....
All open stdio(3) streams are flushed and closed.  Files created by tmpfile(3) are removed.

So i believe leaving main effectively calls the exit function with main's return value. Though I would argue that it is bad style. Personally, I always explicitly free/close any acquired resources.

Evan Teran
This doesn't say anything about other file descriptors, only std{in,out,err} and tmpfiles.
Paul Betts
@Paul, Good one. But beyond streams, it becomes platform specific I think.
Vulcan Eager
POSIX says: All of the file descriptors, directory streams, conversion descriptors, and message catalog descriptors open in the calling process shall be closed [by exit(), _exit(), _Exit()]. But that still applies to hosted implementations - not to embedded, necessarily.
Jonathan Leffler
+3  A: 

Closing file descriptors when you are done using them makes your code more reusable and easier to extend. This sounds to me like a case where you have a valid reason for letting them get closed automatically.

Kevin Beck
+1  A: 

In the beautiful world of embedded platform, it's really hard to say what would happens. However, if I was in your situation, I'd just manually test to see if the file ID are really released.. And, if space is that important, maybe you could document this fact elsewhere.

+2  A: 

Yes, close your file descriptors and free all heap memory, even if you know that the OS will clean it up - that way, when you run valgrind or some similar tool, you don't get a lot of noise in the results, and you can easily recognize "legit" fd leaks.

Paul Betts