LeviX LeviX - 7 days ago 5
C Question

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?

Answer

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.