如何获取符号链接的ctime,mtime,...

时间:2021-08-22 13:24:22

On unix symlinks are pointers to another file. Not only the file but also the symlink has a ctime, mtime, …. I know the symlinks time can be accessed, as ls displays it. If I use one of ruby's File#ctime, File#mtime, …, I always get the attribute of the file the symlink is pointing to, not of the symlink. How can I read this values in ruby? If this is not possible in ruby, tell me how to do it in C. I would write my own c extension in that case.

在unix符号链接上是指向另一个文件的指针。不仅文件而且符号链接都有ctime,mtime,....我知道可以访问符号链接时间,因为ls会显示它。如果我使用ruby的File#ctime,File#mtime,...之一,我总是得到符号链接指向的文件的属性,而不是符号链接。如何在ruby中读取这些值?如果在ruby中这是不可能的,请告诉我如何在C中执行此操作。在这种情况下,我会编写自己的c扩展名。

3 个解决方案

#1


10  

Use File#lstat(). Example:

使用File#lstat()。例:

# This is a dummy symlink; there's no file named "foo".
ln -s foo bar

# Run irb.
irb(main):001:0> File.lstat("bar")
=> #<File::Stat dev=0x801, ino=90113, mode=0120777, nlink=1, uid=1000, gid=1000, rdev=0x0, size=3, blksize=4096, blocks=0, atime=2010-01-05 17:59:06 -0500, mtime=2010-01-05 17:59:05 -0500, ctime=2010-01-05 17:59:05 -0500>

# Get the mtime of the link.
irb(main):002:0> File.lstat("bar").mtime
=> 2010-01-05 17:59:05 -0500

#2


1  

lstat() can do it in C; not sure if there's a Ruby equivalent.

lstat()可以在C中完成;不确定是否有Ruby等价物。

#3


1  

There're not only the attributes of the symlink and the attributes of the final target, but also, if the symlink is itself to another symlink, one or more intermediate steps; to get all the attributes, you'd need to do lstats in a readlink loop.

不仅有符号链接的属性和最终目标的属性,而且如果符号链接本身是另一个符号链接,还有一个或多个中间步骤;要获得所有属性,您需要在readlink循环中执行lstats。

#1


10  

Use File#lstat(). Example:

使用File#lstat()。例:

# This is a dummy symlink; there's no file named "foo".
ln -s foo bar

# Run irb.
irb(main):001:0> File.lstat("bar")
=> #<File::Stat dev=0x801, ino=90113, mode=0120777, nlink=1, uid=1000, gid=1000, rdev=0x0, size=3, blksize=4096, blocks=0, atime=2010-01-05 17:59:06 -0500, mtime=2010-01-05 17:59:05 -0500, ctime=2010-01-05 17:59:05 -0500>

# Get the mtime of the link.
irb(main):002:0> File.lstat("bar").mtime
=> 2010-01-05 17:59:05 -0500

#2


1  

lstat() can do it in C; not sure if there's a Ruby equivalent.

lstat()可以在C中完成;不确定是否有Ruby等价物。

#3


1  

There're not only the attributes of the symlink and the attributes of the final target, but also, if the symlink is itself to another symlink, one or more intermediate steps; to get all the attributes, you'd need to do lstats in a readlink loop.

不仅有符号链接的属性和最终目标的属性,而且如果符号链接本身是另一个符号链接,还有一个或多个中间步骤;要获得所有属性,您需要在readlink循环中执行lstats。