tags:

views:

639

answers:

7

In Unix C programming, is it considered good practice to explicitly close file handles before the process exits, or is it instead good practice to let the OS close the file handles and thus avoid unnecessary code?

Which of the two would generally be considered as the preferred alternative?

Example:

int main (int argc, char* argv[])
{
    int sd;
    sd = socket(...);

    // Snip

   close(sd); // Good or bad practice?
   return 0;
}
+1  A: 

It's very good practice to close the descriptor if your program will go on but the descriptor isn't required anymore.

Then again, it depends on the file descriptor type. close()ing a socket will flush it, for example, and if this fails you may want to retry.

João da Silva
+5  A: 

It's considered good practice to close them yourself.

Probably because it's a good habit, in case your program grows and exit doesn't occur for some time after you finish using a particular "file".

The exceptions are stdin, stdout and stderr which your process did not open.

Incidentally, the UNIX term is "file descriptor".

Darron
+2  A: 

Definitely good practise to close them if you can.

If your program changes so that the file gets closed sooner rather than later you don't need to remember to add that close() later when the file I/O gets refactored.

Alnitak
+2  A: 

I haven't used unix since University, but by relying on unix closing file handles you're reducing the number of ways your code can be used.

You're building in a nightmare for yourself if your code ever needs to be ported to another platform, or if your code needs to be modified to run as a long running service, without explicit resource management you'll soon run out of resources.

Hope you find this helpful,

Binary Worrier
+9  A: 

Generally the code that's doing the opening and closing doesn't know if the process is going to immediately exit - so it's best to include explicit code.

Even if the code is residing on the top-level main() function, it would still be a good idea in case the code is ever re-used.

Douglas Leeder
A: 

I think its almost "universal", if you have OS resources opened you should always close them right after you finnished using them. That way you release those resources so they can be used by other applications.

By relying on the OS to close your handles he is just going to close them when he thinks you no longer need them (app exit for example). You should always release system resources.

Megacan
A: 

The overwhelmingly most important reason it's considered good to close any files you open is so that you can find out about I/O errors and report them to the user. For the same reason, it is probably a good idea to flush (or possibly to close) stdout and stderr if you write to them.

Lars Wirzenius