Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do multiple close calls for one fd in the same function matter?

Tags:

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]

like image 343
j10 Avatar asked Oct 08 '12 13:10

j10


2 Answers

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).

like image 80
Sergey Kalinichenko Avatar answered Nov 23 '22 07:11

Sergey Kalinichenko


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.

like image 22
Art Avatar answered Nov 23 '22 06:11

Art