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. */
34 # include <sys/file.h>
43 # define O_DIRECTORY 0
49 /* Record the location of the current working directory in CWD so that
50 the program may change to other directories and later use restore_cwd
51 to return to the recorded location. This function may allocate
52 space using malloc (via xgetcwd) or leave a file descriptor open;
53 use free_cwd to perform the necessary free or close. Upon failure,
54 no memory is allocated, any locally opened file descriptors are
55 closed; return non-zero -- in that case, free_cwd need not be
56 called, but doing so is ok. Otherwise, return zero.
58 The `raison d'etre' for this interface is that some systems lack
59 support for fchdir, and getcwd is not robust or as efficient.
60 So, we prefer to use the open/fchdir approach, but fall back on
61 getcwd if necessary. Some systems lack fchdir altogether: OS/2,
62 Cygwin (as of March 2003), SCO Xenix. At least SunOS 4 and Irix 5.3
63 provide the function, yet it doesn't work for partitions on which
64 auditing is enabled. */
67 save_cwd (struct saved_cwd
*cwd
)
69 static int have_working_fchdir
= 1;
74 if (have_working_fchdir
)
77 cwd
->desc
= open (".", O_RDONLY
| O_DIRECTORY
);
82 /* On SunOS 4 and IRIX 5.3, fchdir returns EINVAL when auditing
83 is enabled, so we have to fall back to chdir. */
84 if (fchdir (cwd
->desc
))
90 have_working_fchdir
= 0;
94 int saved_errno
= errno
;
101 # endif /* __sun__ || sun */
103 # define fchdir(x) (abort (), 0)
104 have_working_fchdir
= 0;
108 if (!have_working_fchdir
)
110 cwd
->name
= xgetcwd ();
111 if (cwd
->name
== NULL
)
117 /* Change to recorded location, CWD, in directory hierarchy.
118 Upon failure, return nonzero (errno is set by chdir or fchdir).
119 Upon success, return zero. */
122 restore_cwd (const struct saved_cwd
*cwd
)
125 return fchdir (cwd
->desc
) < 0;
127 return chdir (cwd
->name
) < 0;
131 free_cwd (struct saved_cwd
*cwd
)