What happens to file descriptors when the process is killed

file-descriptorsfiles

In my application I open a file, using the open() call.

My questions are:

  • Is the file automatically closed (as using the close() call on the returned file descriptor) if I kill the process?
  • What happens if the application crashes (e.g. segmentation fault)?
  • Is this documented somewhere?

Best Answer

Yes, the file will be automatically closed when the process terminates, regardless of the reason for the process termination.

This is documented in POSIX. In “Consequences of Process Termination”, among other consequences:

  • All of the file descriptors, directory streams, conversion descriptors, and message catalog descriptors open in the calling process shall be closed.

And in “Terminating a Process”:

It is important that the consequences of process termination as described occur regardless of whether the process called _exit() (perhaps indirectly through exit()) or instead was terminated due to a signal or for some other reason.

Related Question