faccessat2 - Linux


Overview

faccessat2 evaluates whether the calling process has the specified access to a file opened by another process. It checks the specified access and the corresponding permissions on the file.

Syntax

faccessat2(int dirfd, const char *pathname, int mode, int flag)

Options/Flags

Required Parameters

  • dirfd: An integer representing the file descriptor of the directory containing the file.
  • pathname: A null-terminated string specifying the path of the file to be checked.
  • mode: An integer specifying the access mode to be checked. Valid options include:
    • F_OK – Checks for file existence.
    • R_OK – Checks for read access.
    • W_OK – Checks for write access.
    • X_OK – Checks for execute access.
    • Logical ORs of the above values to check multiple permissions simultaneously.

Optional Parameter(s)

  • flag: An integer flag that modifies the behavior of the call:
    • AT_EACCESS – Check for effective access rights.
    • AT_NO_AUTOMOUNT – If the file is not found, do not attempt to mount it automatically.
    • AT_SYMLINK_NOFOLLOW – Do not follow symbolic links in the path.

Examples

Check if a file exists:

int fd = open("myfile.txt", O_RDONLY);
if (faccessat2(fd, "myfile.txt", F_OK, 0) == 0) {
    printf("myfile.txt exists.\n");
} else {
    printf("myfile.txt does not exist.\n");
}

Check if a file is readable:

if (faccessat2(fd, "myfile.txt", R_OK, 0) == 0) {
    printf("myfile.txt is readable.\n");
} else {
    printf("myfile.txt is not readable.\n");
}

Check if a symbolic link can be executed:

if (faccessat2(fd, "mylink", X_OK, AT_SYMLINK_NOFOLLOW) == 0) {
    printf("mylink can be executed.\n");
} else {
    printf("mylink cannot be executed.\n");
}

Common Issues

  • Ensure the file descriptor is valid and the file is accessible to the calling process.
  • Check that the pathname is correct and does not contain any errors.
  • If AT_EACCESS is used, make sure the calling process has the proper privileges to check the effective access rights.

Integration

Combine with ls: List files and check their access permissions using faccessat2:

ls -l | while read line; do
    file=$(echo $line | cut -d' ' -f11)
    fd=$(echo $line | cut -d' ' -f1)
    if [ -z "$file" ] || [ ! -d "$file" ]; then continue; fi
    if [ $(faccessat2 $fd $file X_OK) -eq 0 ]; then
        echo "$file is executable."
    else
        echo "$file is not executable."
    fi
done

Related Commands

  • access: Checks the access rights of a file for the current process.
  • stat: Obtains detailed information about a file.
  • open: Opens a file and returns a file descriptor.
  • close: Closes a file descriptor.