On my system (Ubuntu Linux, glibc), man page of a close
call specifies several error return values it can return. It also says
Not checking the return value of close() is a common but nevertheless serious programming error.
and at the same time
Note that the return value should only be used for diagnostics. In particular close() should not be retried after an EINTR since this may cause a reused descriptor from another thread to be closed.
So I am not allowed to ignore the return value nor to retry the call.
Given that, how shall I handle the close()
call failure?
If the error happened when I was writing something to the file, I am probably supposed to try to write the information somewhere else to avoid the data loss.
If I was only reading the file, can I just log the failure and continue the program pretending nothing happened? Are there any caveats, leak of file descriptors or whatever else?
First of all:
EINTR
means exactly that: System call was interrupted, if this happens on aclose()
call, there is exactly nothing you can do.Apart from maybe keeping track of the fact, that if the fd belonged to a file, this file is possibly corrupt, there is not much you can do about errors on
close()
at all - depending on the return value. AFAIK the only case, where a close can be retried is onEBUSY
, but I have yet to see that.So:
close()
might mean that you miss file corruption, especially truncation.close()
just means something has gone awfully wrong outside the scope of your application.In practice,
close
should never be retried on error, and the fd you passed toclose
is always invalid (closed) afterclose
returns, regardless of whether an error occurred. In some cases, an error may indicate that data was lost (certain NFS setups) or unusual hardware conditions for devices (e.g. tape could not be rewound), so you may want to be cautious to avoid data loss, but you should never attempt to close the fd again.In theory, POSIX was unclear in the past as to whether the fd remains open when
close
fails withEINTR
, and systems disagreed. Since it's important to know the state (otherwise you have either fd leaks or double-close bugs which are extremely dangerous in multithreaded programs), the resolution to Austin Group issue #529 specified the behavior strictly for future versions of POSIX, thatEINTR
means the fd remains open. This is the right behavior consistent with the definition ofEINTR
elsewhere, but Linux refuses to accept it. (FWIW there's an easy workaround for this that's possible at the libc syscall wrapper level; see glibc PR #14627.) Fortunately it never arises in practice anyway.Some related questions you might find informative: