通过文件描述符更改“匿名”符号链接的时间戳

通过文件描述符更改“匿名”符号链接的时间戳

futime*函数族的实现是

utimensat(fd, NULL, time, 0)

lutime*那些是用

utimensat(AT_FDCWD, path, time, AT_SYMLINK_NOFOLLOW)

我的最佳猜测来自“获取引用符号链接的文件描述符”部分https://man7.org/linux/man-pages/man7/symlink.7.html就是它:

int fd = open(path, O_PATH | O_NOFOLLOW);
utimensat(fd, NULL, time, AT_SYMLINK_NOFOLLOW);

应该是两全其美,但遗憾的是事实并非如此。

尝试以下变体

#define _GNU_SOURCE

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syscall.h>

#define __NR_openat 257
#define __NR_utimensat 280

struct flags
{
   char o_path;
   char o_nofollow;
   char at_symlink_nofollow;
};

int isX(char c, int flag)
{
    return c == 'x' ? flag : 0;
}

int main(int argc, const char *argv[])
{
    assert(argc == 3);
    const char *path = argv[1];
    assert(strlen(argv[2]) == 3);
    struct flags flags = * (const struct flags *) argv[2];

    // Open the file without following symbolic links
    int fd = openat(AT_FDCWD, path,
        isX(flags.o_path, O_PATH) |
        isX(flags.o_nofollow, O_NOFOLLOW));
    if (fd == -1) {
        perror("open");
        return EXIT_FAILURE;
    }

    // Prepare the time values for access and modification times
    struct timespec times[2] = {
        {
            .tv_sec = 0,
            .tv_nsec = 0,
        },
        {
            .tv_sec = 0,
            .tv_nsec = 0,
        },
    };

    // Update file times using utimensat
    if (syscall(__NR_utimensat, fd, NULL, times,
        isX(flags.at_symlink_nofollow, AT_SYMLINK_NOFOLLOW)) == -1)
    {
        perror("utimensat");
        close(fd);
        return EXIT_FAILURE;
    }

    close(fd);
    printf("File timestamps updated successfully.\n");
    return EXIT_SUCCESS;
}

和脚本

rm -f foo bar
touch foo
ln -s foo bar

for f in foo bar; do
    for y in ooo oox oxo xoo oxx xxo xxx; do
        echo -n "$f $y: "
        ./a.out "$f" "$y";
    done;
done
ls -la foo bar

人们会发现不幸的是,没有任何组合可以在符号链接本身上设置时间戳:

$ ./flutimes.sh
foo ooo: File timestamps updated successfully.
foo oox: utimensat: Invalid argument
foo oxo: File timestamps updated successfully.
foo xoo: utimensat: Bad file descriptor
foo oxx: utimensat: Invalid argument
foo xxo: utimensat: Bad file descriptor
foo xxx: utimensat: Invalid argument
bar ooo: File timestamps updated successfully.
bar oox: utimensat: Invalid argument
bar oxo: open: Symbolic link loop
bar xoo: utimensat: Bad file descriptor
bar oxx: open: Symbolic link loop
bar xxo: utimensat: Bad file descriptor
bar xxx: utimensat: Invalid argument

我想我是在问是否有任何原因无法使其发挥作用?O_PATH | O_NOFOLLOW和不应该AT_SYMLINK_NOFOLLOW成为好朋友,与支持后者的每个系统调用一起工作吗?或者O_PATH用类似的东西替换会更好吗O_METADATA_ONLY

相关内容