3 ms·
> 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 Imagine
by metadat 5y ago
> 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
Imagine how tricky it could be to have to debug this or try to reproduce it? Quite the nasty subtle buggy boundary case, especially in Golang where cleanup deferrment is encouraged and touted in lots of example code.
It's easy to imagine a segment of naive language users completely unknowingly risking creating environments where such a bug can thrive.
It goes like this: first deferring the call to close after opening a file and not receiving an error, then calling close again at the end of the happy path "just to be sure" or because "now I'm done with it". And then blundering along their merry way, believing there is nothing wrong with this and "go has my back".
(1) Common File API abstractions that taste more or less like OOPcombined with (2) defer-capable languages (like Go) where this is the "best practice": This class of bug should be considered common and expected.
The tricky part lies in the gap between being newbie-friendly vs. correct and safe. Language makers can't have it both ways.
Maybe static code analysis could detect it and refuse to compile, as it should be considered a foot-gun type of error.
p.s. notriddle: thank you for inlining complete-ish relevant detailed information in your post. It's nice of you.
- 0xjnml 5y ago> ... especially in Golang where cleanup deferrment is encouraged and touted in lots of example code Go's os.File is not a plain file descriptor. It can be safely closed more than once and will close the underlying FD only the first time the .Close() method is called.