LeviX LeviX - 1 year ago 109
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download