close()

From vegard.wiki
Revision as of 06:47, 18 December 2019 by Vegard (talk | contribs) (new page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

close() is notoriously difficult to get right. You are supposed to check the return value, but not really handle it (other than printing a diagnostic). If you are wrapping a file descriptor using RAII, then you may not be able to throw an exception or return an error if you are calling close() from the destructor.

From the current Linux man page:

A careful programmer will check the return value of close(), since it is quite possi‐ ble that errors on a previous write(2) operation are reported only on the final close() that releases the open file description. Failing to check the return value when closing a file may lead to silent loss of data. This can especially be observed with NFS and with disk quota.

Note, however, that a failure return should be used only for diagnostic purposes (i.e., a warning to the application that there may still be I/O pending or there may have been failed I/O) or remedial purposes (e.g., writing the file once more or cre‐ ating a backup).

Retrying the close() after a failure return is the wrong thing to do, since this may cause a reused file descriptor from another thread to be closed. This can occur because the Linux kernel always releases the file descriptor early in the close oper‐ ation, freeing it for reuse; the steps that may return an error, such as flushing data to the filesystem or device, occur only later in the close operation.

Many other implementations similarly always close the file descriptor (except in the case of EBADF, meaning that the file descriptor was invalid) even if they subse‐ quently report an error on return from close(). POSIX.1 is currently silent on this point, but there are plans to mandate this behavior in the next major release of the standard

A careful programmer who wants to know about I/O errors may precede close() with a call to fsync(2).

Thus, best practice would seem to be:

  • Call fsync() at some point after writing data, but before close(); this should report any I/O errors
  • Only use close() to actually destroy the file descriptor when the file descriptor is no longer in use
  • On Linux, the file descriptor is always closed regardless of the return value (and should therefore not be retried); on other systems, EINTR may signal that the file descriptor was not closed