Gustavo Guedes
Gustavo Guedes

Reputation: 21

What is the difference between closing [close(3)] and clearing [fd_clr(3)] a file descriptor?

I am having problems with an automated software testing, which is blaming use of freed resource when I use fd_clr(3) after using close(3) in a fd. Is there something wrong with doing this?

for(i = 0; i < nfds; ++i) {
    if (FD_ISSET(i, &myFdSet)) {
        close(i);
        FD_CLR(i, &myFdSet);
    }
}

Upvotes: 0

Views: 651

Answers (3)

user4815162342
user4815162342

Reputation: 155196

If the software is really flagging such use of FD_CLR, the automated software is broken. You are removing the closed file descriptor from the watched set, and FD_CLR is precisely the way to do that.

As a work-around, you could transpose the close() and FD_CLR which won't change the meaning of the code, but will appease the buggy analysis tool.

Upvotes: 1

Gem Taylor
Gem Taylor

Reputation: 5613

So, FD_ISSET and FD_CLR are part of the pselect API, read more in the man page here http://man7.org/linux/man-pages/man3/FD_CLR.3.html

It is basically managing a list of all the file numbers you want to wait on, in your next call to pselect, so clearing a file that you have closed makes sense.

Your code is asking, for all the files I was listening for, close the file and remove from the set.

close() actually closes the file. You should not call close multiple times on the same file, or you will see this error. Perhaps some other code is also closing the file?

Upvotes: 1

meaning-matters
meaning-matters

Reputation: 22946

FD_CLR() only changes a local fd_set, which is a C data structure to store info about a list of file descriptors.

close() is a system call that closes the file descriptor.

The fd_set is used in the select() system call. With select() you get information about the state of the list of file descriptors that are stored in your fd_set struct.

The reason why you see the FD_CLR() just below the close(), is that there's no longer need/purpose in asking the state if the closed file descriptor.

Upvotes: 2

Related Questions