问题
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:
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.
回答2:
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.
回答3:
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.
回答4:
The one concern I would have with regard to leaving closing off file-descriptors to automatic cleanup, would be how much you care about any data you've written to said file-descriptors and if you reasonably can deal with a failure to write.
write() need not block (depending on how it were open()ed in the first place) and wait for data to successfully commit, so there are cases where close can fail because the underlying sub-system fails to commit the pending write, and thus close exits with failure and sets errno to EIO, and depending on what you just wrote, you may or may not want to take some corrective action.
Admittedly, this is a corner case where you REALLY care about data consistency, i.e. a DBMS type applications or reporting sucess/failure of a backup. In many (most?) cases it doesn't really matter all that much, and you'll be fine leaving off close() to process cleanup/exit.
回答5:
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.
来源:https://stackoverflow.com/questions/282992/is-there-a-need-to-close-file-descriptors-before-exit