I just want to know what is the behavior of having two consecutive close on a fd.
e.g.-
close(fd); close(fd);
[fd is an int]
The first call should return 0
; the second call should return -1
, and set errno
to EBADF
.
You should prevent the second call from happening by setting fd
to a known bad number, e.g. a -1
immediately after the first call of close
, and subsequently checking fd
before making the second call (and not making the call if fd
is -1
):
close(fd); fd = -1; ... // More code ... if (fd != -1) { close(fd) fd = -1; }
This code pattern will help when you need to make calls to close
from multiple places, but you are not sure if the file is open, or if it has been closed already. Passing -1
to close
is harmless (you would get an EBADF
, of course).
It should be harmless unless you're threaded or doing something between the two calls to close. Then you might end up closing an fd that something else in your program has opened.
The way threading is relevant is that libraries almost always do weird things behind your back. Libc will open files for looking up error messages or other locale dependent stuff, the resolver can open configuration files, etc. If you close a file descriptor and close it again, in a threaded environment you can easily end up in a situation where the file descriptor has been reused by a library and you close it behind its back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With