is it a good practice to close file descriptors on exit

后端 未结 6 624
南方客
南方客 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:27

    C does guarantee that all open files will be closed if your program terminates normally (i.e. via exit or a return from main). However, if your program terminates abnormally, e.g. it's closed by the operating system due to using a NULL pointer, it's up to the operating system to close the files. Therefore it's a good idea to make sure files are closed once they're no longer needed in case of unexpected termination.

    The other reason is resource limits. Most operating systems have limits on the number of files open (as well as many other things), and so it's good practice to return those resources as soon as they're no longer needed. If every program kept all its files open indefinitely, systems could run into problems quite quickly.

提交回复
热议问题