What does closing an invalid file descriptor do?

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

int fd; // open a file if(fd == -1) { close(fd); } 

It looks very wrong to me.

Does the invalid file handle close?

+5
source share
2 answers

According to the manual:

After successful completion, the value 0 is returned. Otherwise, the value is from -1 and the global integer variable errno is set to indicate an error.

and then:

  The close() system call will fail if: [EBADF] fildes is not a valid, active file descriptor. 

Then nothing harmful will happen.

+4
source

It returns an error code. There is nothing wrong, but it is also not useful, since in any case the return values ​​are not checked.

Citation reference page

Return value

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

and

Mistakes

EBADF
fd not a valid open file descriptor.

+4
source

Source: https://habr.com/ru/post/1260662/


All Articles