dirfd - Linux


dirfd returns the file descriptor of the given directory. It is primarily used to determine the file descriptor of a directory stream opened by other system calls, such as open, openat, or fdopendir.






Find the file descriptor of the current working directory:

$ dirfd .

Get the file descriptor of a directory stream opened using openat:

$ fd=$(openat /proc 1 0)
$ dirfd "$fd"

Common Issues

  • Invalid file descriptor: Ensure that the specified directory stream is valid and open.
  • Incorrect usage: dirfd can only be used with directory streams. Attempting to use it with regular files or other file types will result in an error.


dirfd can be combined with other commands to:

  • Get file information: Use stat to retrieve detailed information about the directory corresponding to the file descriptor.
  • Close file descriptor: Use close to close the directory stream associated with the file descriptor.
  • Create directory junction: Use mount with the –bind option to create a directory junction using the file descriptor as the source.

Related Commands

  • open: Open or create a file.
  • openat: Open or create a file relative to the specified directory.
  • stat: Display file or directory information.
  • close: Close a file descriptor.
  • mount: Mount a file or directory.