Note: Please read to the end before marking this as duplicate. While it's similar, the scope of what I'm looking for in an answer extends beyond what the previous question was asking for.
Widespread practice, which I tend to agree with, tends to be treating close
purely as a resource-deallocation function for file descriptors rather than a potential IO operation with meaningful failure cases. And indeed, prior to the resolution of issue 529, POSIX left the state of the file descriptor (i.e. whether it was still allocated or not) unspecified after errors, making it impossible to respond portably to errors in any meaningful way.
However, a lot of GNU software goes to great lengths to check for errors from close
, and the Linux man page for close
calls failure to do so "a common but nevertheless serious programming error". NFS and quotas are cited as circumstances under which close
might produce an error but does not give details.
What are the situations under which close
might fail, on real-world systems, and are they relevant today? I'm particularly interested in knowing whether there are any modern systems where close
fails for any non-NFS, non-device-node-specific reasons, and as for NFS or device-related failures, under what conditions (e.g. configurations) they might be seen.
Consider the inverse of your question: "Under what situations can we guarantee that
close
will succeed?" The answer is:close
in this OS and Kernel versionIf you are convinced that you program doesn't have any logic errors and you have complete control over the Kernel and file system, then you don't need to check the return value of
close
.Otherwise, you have to ask yourself how much you care about diagnosing problems with
close
. I think there is value in checking and logging the error for diagnostic purposes:close
, then you'll be able to quickly track it down. This may help to catch a bug early before it causes problems.close
does return an error when (for example) data was not flushed, then you'll be able to quickly diagnose why the data got corrupted. It's an easy red flag because you know the error should not occur.Once upon a time (24 march, 2007), Eric Sosman had the following tale to share in the comp.lang.c newsgroup: