openKylin论坛

 找回密码

Linux下如何知道文件被那个进程写 [复制链接]

本文转自:http://rdc.taobao.com/blog/cs/?p=1758

晚上朔海同学问:
一个文件正在被进程写 我想查看这个进程 文件一直在增大 找不到谁在写 使用lsof也没找到


这个问题挺有普遍性的,解决方法应该很多,这里我给大家提个比较直观的方法。
linux下每个文件都会在某个块设备上存放,当然也都有相应的inode, 那么透过vfs.write我们就可以知道谁在不停的写入特定的设备上的inode。
幸运的是systemtap的安装包里带了inodewatch.stp,位于/usr/local/share/doc/systemtap/examples/io目录下,就是用来用途的。
我们来看下代码:
  1. $ cat inodewatch.stp
  2. #! /usr/bin/env stap

  3. probe vfs.write, vfs.read
  4. {
  5.   # dev and ino are defined by vfs.write and vfs.read
  6.   if (dev == MKDEV($1,$2) # major/minor device
  7.       && ino == $3)
  8.     printf ("%s(%d) %s 0x%x/%u\n",
  9.       execname(), pid(), probefunc(), dev, ino)
  10. }
复制代码
这个脚本的使用方法如下: stap  inodewatch.stp major minor ino下面我们构造个场景: dd不停的写入一个文件,查出这个文件的ino, 以及它所在设备的major, minor, 运行stap脚本就可以得到答案。

场景交代好了,我们来演示下:
  1. $ pwd
  2. /home/chuba
  3. $ df
  4. Filesystem           1K-blocks      Used Available Use% Mounted on
  5. ...
  6. /dev/sdb1            1621245336 825209568 713681236  54% /home
  7. ...
  8. $ ls -al /dev/sdb1
  9. brw-rw---- 1 root disk 8, 17 Oct 24 11:22 /dev/sdb1
  10. $ rm -f test.dat && dd if=/dev/zero of=test.dat
  11. ^C9912890+0 records in
  12. 9912890+0 records out
  13. 5075399680 bytes (5.1 GB) copied, 26.8189 s, 189 MB/s
复制代码
这个终端模拟文件的不停写入,同时在另外一个终端才查收谁干的。这里我们已经知道设备的major/minor为8/17
  1. $ stat -c '%i' test.dat
  2. 25337884
  3. $ sudo stap /usr/local/share/doc/systemtap/examples/io/inodewatch.stp 8 17 25337884
  4. dd(740) vfs_write 0x800011/25337884
  5. dd(740) vfs_write 0x800011/25337884
  6. dd(740) vfs_write 0x800011/25337884
  7. dd(740) vfs_write 0x800011/25337884
  8. dd(740) vfs_write 0x800011/25337884
  9. dd(740) vfs_write 0x800011/25337884
  10. <code class="bash plain">...</code>
复制代码
看到了吧,dd是罪魁祸首,pid是740, 搞定收工!
小结: systemtap处理这种问题很是神器。
祝玩得开心!



楼主
发表于 2013-8-13 14:36:41
回复

使用道具 举报

openKylin

GMT+8, 2024-5-14 11:15 , Processed in 0.019411 second(s), 17 queries , Gzip On.

Copyright ©2022 openKylin. All Rights Reserved .

ICP No. 15002470-12 Tianjin

快速回复 返回顶部 返回列表