1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* save-cwd.c -- Save and restore current working directory.
5 Copyright (C) 1995, 1997-1998, 2003-2006, 2009-2010 Free Software
8 This program is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 /* Written by Jim Meyering. */
33 #include "chdir-long.h"
38 #if GNULIB_FCNTL_SAFER
41 # define GNULIB_FCNTL_SAFER 0
44 /* On systems without the fchdir function (WOE), pretend that open
45 always returns -1 so that save_cwd resorts to using xgetcwd.
46 Since chdir_long requires fchdir, use chdir instead. */
49 # define open(File, Flags) (-1)
51 # define fchdir(Fd) (abort (), -1)
53 # define chdir_long(Dir) chdir (Dir)
56 /* Record the location of the current working directory in CWD so that
57 the program may change to other directories and later use restore_cwd
58 to return to the recorded location. This function may allocate
59 space using malloc (via xgetcwd) or leave a file descriptor open;
60 use free_cwd to perform the necessary free or close. Upon failure,
61 no memory is allocated, any locally opened file descriptors are
62 closed; return non-zero -- in that case, free_cwd need not be
63 called, but doing so is ok. Otherwise, return zero.
65 The `raison d'etre' for this interface is that the working directory
66 is sometimes inaccessible, and getcwd is not robust or as efficient.
67 So, we prefer to use the open/fchdir approach, but fall back on
70 Some systems lack fchdir altogether: e.g., OS/2, pre-2001 Cygwin,
71 SCO Xenix. Also, SunOS 4 and Irix 5.3 provide the function, yet it
72 doesn't work for partitions on which auditing is enabled. If
73 you're still using an obsolete system with these problems, please
74 send email to the maintainer of this code. */
77 save_cwd (struct saved_cwd *cwd)
81 cwd->desc = open (".", O_SEARCH);
82 if (!GNULIB_FCNTL_SAFER)
83 cwd->desc = fd_safer (cwd->desc);
86 cwd->name = xgetcwd ();
87 return cwd->name ? 0 : -1;
90 set_cloexec_flag (cwd->desc, true);
94 /* Change to recorded location, CWD, in directory hierarchy.
95 Upon failure, return -1 (errno is set by chdir or fchdir).
96 Upon success, return zero. */
99 restore_cwd (const struct saved_cwd *cwd)
102 return fchdir (cwd->desc);
104 return chdir_long (cwd->name);
108 free_cwd (struct saved_cwd *cwd)