1 /* save-cwd.c -- Save and restore current working directory.
2 Copyright (C) 1995, 1997, 1998, 2003 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 2, or (at your option)
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, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by Jim Meyering. */
37 # include <sys/file.h>
46 # define O_DIRECTORY 0
52 /* Record the location of the current working directory in CWD so that
53 the program may change to other directories and later use restore_cwd
54 to return to the recorded location. This function may allocate
55 space using malloc (via xgetcwd) or leave a file descriptor open;
56 use free_cwd to perform the necessary free or close. Upon failure,
57 no memory is allocated, any locally opened file descriptors are
58 closed; return non-zero -- in that case, free_cwd need not be
59 called, but doing so is ok. Otherwise, return zero.
61 The `raison d'etre' for this interface is that some systems lack
62 support for fchdir, and getcwd is not robust or as efficient.
63 So, we prefer to use the open/fchdir approach, but fall back on
64 getcwd if necessary. Some systems lack fchdir altogether: OS/2,
65 Cygwin (as of March 2003), SCO Xenix. At least SunOS4 and Irix 5.3
66 provide the function, yet it doesn't work for partitions on which
67 auditing is enabled. */
70 save_cwd (struct saved_cwd *cwd)
72 static int have_working_fchdir = 1;
77 if (have_working_fchdir)
80 cwd->desc = open (".", O_RDONLY | O_DIRECTORY);
85 /* On SunOS 4 and IRIX 5.3, fchdir returns EINVAL when auditing
86 is enabled, so we have to fall back to chdir. */
87 if (fchdir (cwd->desc))
93 have_working_fchdir = 0;
97 int saved_errno = errno;
104 # endif /* __sun__ || sun */
106 # define fchdir(x) (abort (), 0)
107 have_working_fchdir = 0;
111 if (!have_working_fchdir)
113 cwd->name = xgetcwd ();
114 if (cwd->name == NULL)
120 /* Change to recorded location, CWD, in directory hierarchy.
121 Upon failure, return nonzero (errno is set by chdir or fchdir).
122 Upon success, return zero. */
125 restore_cwd (const struct saved_cwd *cwd)
128 return fchdir (cwd->desc) < 0;
130 return chdir (cwd->name) < 0;
134 free_cwd (struct saved_cwd *cwd)