Directories and Links 365
The equivalent using chdir() is as follows:
char buf[PATH_MAX];
getcwd(buf, PATH_MAX); /* Remember where we are */
chdir(somepath); /* Go somewhere else */
chdir(buf); /* Return to original directory */
18.11 Operating Relative to a Directory File Descriptor
Starting with kernel 2.6.16, Linux provides a range of new system calls that perform
similar tasks to various traditional system calls, but provide additional functionality
that is useful to some applications. These system calls are summarized in Table 18-2.
We describe these system calls in this chapter because they provide variations on
the traditional semantics of the process’s current working directory.
In order to describe these system calls, we’ll use a specific example: openat().
Table 18-2: System calls that use a directory file descriptor to interpret relative pathnames
New
interface
Traditional
analog
Notes
faccessat() access() Supports AT_EACCESS and AT_SYMLINK_NOFOLLOW flags
fchmodat() chmod()
fchownat() chown() Supports AT_SYMLINK_NOFOLLOW flag
fstatat() stat() Supports AT_SYMLINK_NOFOLLOW flag
linkat() link() Supports (since Linux 2.6.18) AT_SYMLINK_FOLLOW flag
mkdirat() mkdir()
mkfifoat() mkfifo() Library function layered on top of mknodat()
mknodat() mknod()
openat() open()
readlinkat() readlink()
renameat() rename()
symlinkat() symlink()
unlinkat() unlink() Supports AT_REMOVEDIR flag
utimensat() utimes() Supports AT_SYMLINK_NOFOLLOW flag
#define _XOPEN_SOURCE 700 /* Or define _POSIX_C_SOURCE >= 200809 */
#include <fcntl.h>
int openat(int dirfd, const char *pathname, int flags, ... /* mode_t mode */);
Returns file descriptor on success, or –1 on error