touch -t 如何在内部工作?

syn*_*gma 20 date timestamps files

touch -t命令在内部是如何工作的(我试图找到它的源代码但找不到)?

fro*_*utz 30

有时您甚至不需要源代码。使用strace.

$ strace touch -t 201212121212 foobar
execve("/usr/bin/touch", ["touch", "-t", "201212121212", "foobar"], [/* 61 vars */]) = 0
[...] lots of noise [...]
open("foobar", O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, 0666) = 3
dup2(3, 0)                              = 0
close(3)                                = 0
utimensat(0, NULL, {{1355310720, 0}, {1355310720, 0}}, 0) = 0
close(0)                                = 0
close(1)                                = 0
close(2)                                = 0
exit_group(0)                           = ?
+++ exited with 0 +++
Run Code Online (Sandbox Code Playgroud)

为什么你好,utimensat()。你是做什么的?

$ man utimensat

NAME
   utimensat, futimens - change file timestamps with nanosecond precision
Run Code Online (Sandbox Code Playgroud)

所以有一个函数可以更改文件时间戳,并touch使用它来更新文件的时间戳。这就是它内部的运作方式。


Gil*_*il' 24

touch调用utimes系统调用来设置文件的修改时间和访问时间。在某些系统上utimes,它不是,而是打开文件,然后通过描述符设置文件时间,例如utimensat在 Linux 下。

您可以touch通过查看系统调用来了解系统的工作方式。在 Linux 下,使用strace,例如strace touch -d '1 hour ago' foo.

在哪里可以找到源代码取决于您的操作系统。GNU 版本在coreutils 中,在任何 BSD 的主源代码树中有一个版本,在BusyBox 中有一个版本,在Minix等中。


jll*_*gre 11

以下是它在 Solaris 上的工作方式。truss被用来代替stracewhich 在这里是一个完全不同的命令。

就像在 Gnu/Linux 下一样,使用的utimensat是系统调用。

$ truss -vall -u a.out -f touch -t 1306080000 z
4160:   execve("/usr/bin/touch", 0xF0770FC0, 0xF0770FD4)  argc = 4
...
4160/1@1:       -> main(0x4, 0xf0770fc0, 0xf0770fd4, 0xf0770f7c)
...
4160/1@1:           -> atoi_for2(0xf0771131, 0x0, 0x24, 0xebc95be0)
4160/1@1:           <- atoi_for2() = 13
4160/1@1:           -> atoi_for2(0xf0771133, 0x0, 0x24, 0xebc95be0)
4160/1@1:           <- atoi_for2() = 6
4160/1@1:           -> atoi_for2(0xf0771135, 0x0, 0x24, 0xebc95be0)
4160/1@1:           <- atoi_for2() = 8
4160/1@1:           -> atoi_for2(0xf0771137, 0x0, 0x24, 0xebc95be0)
4160/1@1:           <- atoi_for2() = 0
4160/1@1:           -> atoi_for2(0xf0771139, 0x0, 0x24, 0xebc95be0)
4160/1@1:           <- atoi_for2() = 0
4160/1@1:         <- parse_time() = 0x51b257e0
4160/1:         stat64("z", 0xF0770ED0)                         = 0
4160/1:             d=0x08A00002 i=75783706 m=0100644 l=1  u=100   g=10    sz=0
4160/1:                 at = Jun  8 01:48:08 CEST 2013  [ 1370648888.022270973 ]
4160/1:                 mt = Jun  8 01:48:08 CEST 2013  [ 1370648888.022270973 ]
4160/1:                 ct = Jun  8 01:48:08 CEST 2013  [ 1370648888.022273810 ]
4160/1:             bsz=4096  blks=0     fs=tmpfs
4160/1:         utimensat(AT_FDCWD, "z", 0xF0770F60, 0)         = 0
4160/1:                 at = Jun  8 00:00:00 CEST 2013  [ 1370642400.000000000 ]
4160/1:                 mt = Jun  8 00:00:00 CEST 2013  [ 1370642400.000000000 ]
4160/1@1:       <- main() = 0
4160/1@1:       -> _fini()
4160/1@1:       <- _fini() = 0xebcc0140
4160/1:         _exit(0)
Run Code Online (Sandbox Code Playgroud)