is it a good practice to close file descriptors on exit

后端 未结 6 611
南方客
南方客 2020-12-15 17:56

If for some reason, I discover a fatal situation in my program, and I would like to exit with an error code. Sometimes, the context of the fatal error is outside the scope o

6条回答
  •  暖寄归人
    2020-12-15 18:31

    Every sane operating system (certainly any form of Linux, or Windows) will close the files when the program terminates. If you have a very simple program then you probably don't need to close files on termination. However closing the files explicitly is still good practice, for the following reasons:

    1. if you leave it to the OS you have no control over the order in which the files are closed, which may lead to consistency problems (such as in a multi-file database).

    2. if there are errors associated with closing the file (such as I/O errors, out of space errors, etc) you have no way of reporting them.

    3. there may be interactions with file locking which need to be handled.

    4. a routine to close all files can handle any other clean-up that the program needs at the same time (flushing buffers, for instance)

提交回复
热议问题