Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does closing an invalid file descriptor do?

Tags:

c

file-io

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?

like image 740
LeviX Avatar asked Dec 01 '16 16:12

LeviX


People also ask

What does closing a file descriptor do?

close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).

What happens if you don't close a file descriptor?

As long as your program is running, if you keep opening files without closing them, the most likely result is that you will run out of file descriptors/handles available for your process, and attempting to open more files will fail eventually.

Do I need to close a file descriptor?

It is probably unwise to close file descriptors while they may be in use by system calls in other threads in the same process. Since a file descriptor may be reused, there are some obscure race conditions that may cause unintended side effects.

What does close () do in C?

DESCRIPTION. The close() function shall deallocate the file descriptor indicated by fildes. To deallocate means to make the file descriptor available for return by subsequent calls to open() or other functions that allocate file descriptors.


1 Answers

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.

like image 61
Jean-Baptiste Yunès Avatar answered Sep 26 '22 08:09

Jean-Baptiste Yunès