The classic guide to POSIX programming "Advanced programming in UNIX environment" states:
When a process terminates, all of its open files are closed automatically by the kernel. Many programs take advantage of this fact and don't explicitly close open files.
You did not mention the OS in your question but such behavior should be expected from any OS. Whenever your program control flow crosses exit()
or return
from main()
it is the system responsibility to clean up after the process.
There is always a danger of bugs in OS implementation. But, on the other hand, system has to deallocate way more than several open file descriptors at the process termination: memory occupied by the executable file image, stack, kernel objects associated with the process. You can not control this behavior from the user space, you just rely on its working-as-intended. So, why can't a programmer rely on the automatic close of the fd
s?
So, the only problem with leaving fd
s open may be the programming style question. And, as in the case of using stdio
objects (i.e. stuff built around the system-provided file i/o), you may get (somewhat) disorienting alerts while valgrinding. As for the danger of leaking system resources, there should be nothing to worry about, unless your OS implementation is really buggy.
exit
function, or a return frommain
. – Extravasation