原理:在linux系统的/proc分区下保存着进程的名字和目录,包含fd(文件描述符)和其下的子目录(进程打开文件的链接),那么如果进程正在调用文件,删除了一个文件,还存在一个inode的引用:/proc/进程号/fd/文件描述符;我们只要知道当前打开文件的进程pid和文件描述符fd就能利用lsof工具列出进程打开的文件。

      一、将 ls 的手册过滤掉主要控制符后重定向到文件ls.txt 中,并用more查看,CTRL + Z 暂停查看操作:

 
  
1: [root@localhost script]# man ls |col -b > ls.txt
  2: [root@localhost script]# more ls.txt
  3: LS(1)                            User Commands                           LS(1)
  4: 
 
  
  1: [1]+  Stopped                 more ls.txt
  2: [root@localhost script]#
  3: [root@localhost script]# jobs
  4: [1]+  Stopped                 more ls.txt
  5: 
 
    二、假设我们误删文件 ls.txt
 
  1: [root@localhost script]# rm ls.txt
  2: rm:是否删除 一般文件 “ls.txt”? y
    
    三、利用lsof找到进程6511、并拷贝恢复,只能在这个文件被使用或调用的情况下有效:
 
 
  
 
  

[root@localhost script]# lsof |grep ls.txt

  

  4: more      6511      root    3r      REG      253,0     7300    1083699 /opt/script/ls.txt (deleted)
  5: 
 
  
  1: [root@localhost script]# ls -l /proc/6511/fd/
  2: 0  1  2  3
  3: [root@localhost script]# ls -l /proc/6511/fd/3
  4: lr-x------ 1 root root 64 10-30 21:21 /proc/6511/fd/3 -> /opt/script/ls.txt (deleted)
  5: 
 
  
 1: cp /proc/6511/fd/3 ls.txt.saved
  2: