Skip to content
class method · added in Ruby 3.3

Dir.fchdir

(::int) -> ::Integer
[T] (::int) { () -> T } -> T
Dir.fchdir(fd) → 0
Dir.fchdir(fd) { ... } → object

Changes the current working directory to the directory specified by the integer file descriptor fd.

When passing a file descriptor over a UNIX socket or to a child process, using fchdir instead of chdir avoids the time-of-check to time-of-use vulnerability

With no block, changes to the directory given by fd:

Example
Dir.chdir('/var/spool/mail')
Dir.pwd # => "/var/spool/mail"
dir  = Dir.new('/usr')
fd = dir.fileno
Dir.fchdir(fd)
Dir.pwd # => "/usr"

With a block, temporarily changes the working directory:

  • Calls the block with the argument.

  • Changes to the given directory.

  • Executes the block (yields no args).

  • Restores the previous working directory.

  • Returns the block’s return value.

Example:

Example
Dir.chdir('/var/spool/mail')
Dir.pwd # => "/var/spool/mail"
dir  = Dir.new('/tmp')
fd = dir.fileno
Dir.fchdir(fd) do
  Dir.pwd # => "/tmp"
end
Dir.pwd # => "/var/spool/mail"

This method uses the fchdir() function defined by POSIX 2008; the method is not implemented on non-POSIX platforms (raises NotImplementedError).

Raises an exception if the file descriptor is not valid.

In a multi-threaded program an error is raised if a thread attempts to open a chdir block while another thread has one open, or a call to chdir without a block occurs inside a block passed to chdir (even in the same thread).

Ruby version changes

  1. 3.3
    • Dir.fchdir added for changing the directory to the directory specified by the provided directory file descriptor. [Feature #19347]

See also .exist? .foreach .entries .for_fd also in 4.1 · 3.4 · 3.3