1 /* provide a replacement fdopendir function
2 Copyright (C) 2004-2009 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* written by Jim Meyering */
27 #include "openat-priv.h"
30 /* Replacement for Solaris' function by the same name.
31 <http://www.google.com/search?q=fdopendir+site:docs.sun.com>
32 First, try to simulate it via opendir ("/proc/self/fd/FD"). Failing
33 that, simulate it by using fchdir metadata, or by doing
34 save_cwd/fchdir/opendir(".")/restore_cwd.
35 If either the save_cwd or the restore_cwd fails (relatively unlikely),
36 then give a diagnostic and exit nonzero.
37 Otherwise, this function works just like Solaris' fdopendir.
40 Unlike other fd-related functions, this one effectively consumes
41 its FD parameter. The caller should not close or otherwise
42 manipulate FD if this function returns successfully. Also, this
43 implementation does not guarantee that dirfd(fdopendir(n))==n;
44 the open directory stream may use a clone of FD, or have no
45 associated fd at all. */
52 char buf[OPENAT_BUFFER_SIZE];
53 char *proc_file = openat_proc_name (buf, fd, ".");
56 dir = opendir (proc_file);
62 saved_errno = EOPNOTSUPP;
65 /* If the syscall fails with an expected errno value, resort to
66 save_cwd/restore_cwd. */
67 if (! dir && EXPECTED_ERRNO (saved_errno))
70 const char *name = _gl_directory_name (fd);
74 #else /* !REPLACE_FCHDIR */
75 struct saved_cwd saved_cwd;
76 if (save_cwd (&saved_cwd) != 0)
77 openat_save_fail (errno);
89 if (restore_cwd (&saved_cwd) != 0)
90 openat_restore_fail (errno);
93 free_cwd (&saved_cwd);
94 #endif /* !REPLACE_FCHDIR */