How to find which process a file is being written by in Linux?

  sonic0002        2013-03-16 21:44:35       4,738        0    

Some people ask a file is being written by one process and they want to check this process, but they cannot find the process even with sof.

This question is very common and there are many solutions, here we introduce a straightforward method.

In Linux, each file will be stored on one device and of course there will be a relative inode, then we can use vfs.write to know who is writing the inode on one specified device continuously. Luckily there is inodewatch.stp in the installation package of systemtap, it locates at /usr/local/share/doc/systemtap/examples/io. It is used foe above.

Let take a look at the code:

  1. "color:rgb(85, 85, 85)">$ 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. }

This usage of this method is stap inodewatch.stp major minor ino. Let's create this scenario,: dd will continuously write on one file, we find out the ino of this file and its major and minor of its device, we can find the answer by executing stap.

Let's take a look at the scenario codes:

  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

This terminal will simulate the file write, at the same time another terminal will check which process is doing this. Here we can find the major/minor of the device is 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. ...

Have you noticed that dd is the process, PID is 740. It's done. Mission completed.

Source : http://blog.yufeng.info/archives/2581

LINUX  PROCESS  FILE WRITE 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

X.com

Homepage of x.com. What's the story behind it? @Elon Musk