Home > Back-end >  Should I close file descriptor passed to fchdir?
Should I close file descriptor passed to fchdir?

Time:11-05

When I want to change directory using a file descriptor, should I close the directory FD after calling fchdir, or the fchdir closes the FD automatically?

int fd = open(…);
if (fd == -1) error();
fchdir(fd);
//close(fd);

CodePudding user response:

IMHO, if the code is done with fd to never use it again, call close.

The call to fchdir will not close the file descriptor (see the posix description of fchdir ).

fchdir likely (depends on OS and file system) obtains the needed information from fd before returning to the caller. Here is an example of how one specific OS file system handles system calls for fchdir

For a more informed decision whether you should or should not close fd investigate the description of close:

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. All outstanding record locks owned by the process on the file associated with the file descriptor shall be removed (that is, unlocked).

  • Related