LeviX LeviX - 6 months ago 45
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)

This looks very wrong to me.

Is closing an invalid file descriptor valid?


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.