【问题标题】:Use of lsof Commandlsof 命令的使用
【发布时间】:2020-07-20 14:05:42
【问题描述】:

当我在 Python 程序中打开文件时

sptxt = open('output.txt','w')

然后运行以下命令:

i@raspberrypi:~/Watson $ lsof /home/pi/Watson/output.txt
COMMAND     PID USER   FD   TYPE DEVICE SIZE/OFF   NODE NAME
python3.7 16665   pi    6w   REG  179,2        0 645827 /home/pi/Watson/output.txt

如果我只是通过文本编辑器打开 output.txt 并运行与上面相同的命令,我不会得到任何结果。

为什么? 有没有办法确定它是否被文本编辑器打开?

【问题讨论】:

    标签: lsof


    【解决方案1】:

    简短的回答是文本编辑器没有打开文件。 更长的答案是,文本编辑器通常比人们想象的更精巧。

    让我们看看不起眼的vim 编辑器。

    为了准备,创建一个名为 demo.txt 的文件并添加几行。

    Now is the time
    for all good men
    

    现在使用strace 看看vi 在做什么:

    strace -frt -o myfile.txt vi demo.txt
    

    在文件中间添加新行,保存退出。

    strace 输出的关键部分如下所示:

    ...
    15850      0.000037 unlink("demo.txt~") = -1 ENOENT (No such file or directory)
    15850 (1)  0.000034 rename("demo.txt", "demo.txt~") = 0
    15850 (2)  0.000055 open("demo.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644) = 3
    15850 (3)  0.000044 write(3, "Now is the time\nadding a new lin"..., 51) = 51
    15850      0.000042 fsync(3)            = 0
    15850      0.003511 stat("demo.txt", {st_mode=S_IFREG|0644, st_size=51, ...}) = 0
    15850      0.000039 stat("demo.txt", {st_mode=S_IFREG|0644, st_size=51, ...}) = 0
    15850 (4)  0.000033 close(3)            = 0
    15850 (5)  0.000029 chmod("demo.txt", 0100644) = 0
    15850      0.000037 setxattr("demo.txt", "system.posix_acl_access", "\x02\x00\x00\x00\x01\x00\x06\x00\xff\xff\xff\xff\x04\x00\x04\x00\xff\xff\xff\xff \x00\x04\x00\xff\xff\xff\xff", 28, 0) = 0
    15850      0.000091 write(1, " 3L, 51C written", 16) = 16
    15850      0.000040 lseek(4, 0, SEEK_SET) = 0
    15850      0.000029 write(4, "b0VIM 7.4\0\0\0\0\20\0\0\274\267\25_\324\35\6\0\352=\0\0myuser"..., 4096) = 4096
    15850      0.000040 stat("/home/myuser/demo.txt", {st_mode=S_IFREG|0644, st_size=51, ...}) = 0
    15850 (6)  0.000046 unlink("demo.txt~") = 0
    ...
    

    查看vim 在此处执行的操作,在保存时快速连续:

    1. 将文件重命名为带有波浪号 (demo.txt~) 的备份文件
    2. 以写入模式打开 demo.txt 作为文件描述符 3
    3. 编写新修改的文​​本。
    4. 关闭文件 (FD 3)
    5. 对新版本的文件执行chmod等。
    6. 删除暂存文件。

    所有这些步骤都非常快地完成,只有在给出“写入文件”命令时。 您可以在vim 中编辑文件并在单独的进程中修改该文件,vim 不会对它做任何事情,直到您尝试保存文件,此时它会警告您。

    其他编辑可能也在做类似的事情。您可以使用strace 来查看他们正在执行什么样的系统调用,并将其与您在lsof 中看到的相关联。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-19
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多