LeviX
LeviX

Reputation: 3167

What does closing an invalid file descriptor do?

I have some legacy code that does this all over the place:

int fd; // open a file 

if(fd == -1)
{
    close(fd);
}

This looks very wrong to me.

Is closing an invalid file descriptor valid?

Upvotes: 9

Views: 5219

Answers (3)

braindigitalis
braindigitalis

Reputation: 558

note that in windows msvc, calling close with an invalid fd causes an abort() to occur by means of an assertion. the fd is checked it is greater than or equal to 0 and less than some magic number "nhandle" (which has the value of 64 on my system) not even an exception you can catch, or returning -1. it just bombs.

you'll get something like this (screenshot thanks to one of the users of my library):

enter image description here

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

It returns an error code.There is nothing wrong but it is not useful either, as there is no check made on the return value anyway.

Quoting the man page

Return Value

close() returns zero on success. On error, -1 is returned, and errno is set appropriately.

and

Errors

EBADF
fd isn't a valid open file descriptor.

Upvotes: 5

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36391

According to manual:

Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 is returned and the global integer variable errno is set to indicate the error.

and then:

 The close() system call will fail if:

 [EBADF]            fildes is not a valid, active file descriptor.

Then nothing harmful will happen.

Upvotes: 9

Related Questions