Custom Search
Showing posts with label lsof. Show all posts
Showing posts with label lsof. Show all posts

Wednesday, April 20, 2016

How to use lsof to find information about files opened by a process

1)
Open a file with vim editor and don't close it
$vim myfile1.txt

2)
Find PID of vim process
$ps -aux | grep vim
saju      6570  0.1  0.0  76332  6260 pts/10   Sl+  02:43   0:00 vim myfile1.txt

3)
check lsof the vim process and you can see the process opened one file
$sudo lsof -p 6570
vim     6570 saju    5u   REG    8,1    12288 17328734 /home/saju/testdownload/.myfile1.txt.swp

* Here 5u is the file descriptor (fd)

4)
Open another file in same vim editor with ":split myfile2.txt" command

5)
check lsof the process and you can see the process opened two files
$sudo lsof -p 6570
vim     6570 saju    5u   REG    8,1    12288 17328734 /home/saju/testdownload/.myfile1.txt.swp
vim     6570 saju    6u   REG    8,1    12288 17328754 /home/saju/testdownload/.myfile2.txt.swp

* Here 5u and 6u are the file descriptor (fd)

Ubuntu Linux Recover Deleted Files With lsof

1)
Create a file
$vim myfile1.txt

2)
Open that file with program "tail"
$tail -f myfile1.txt

3)
Delete that file
$rm myfile1.txt

4)
Find PID of process which opened "myfile1.txt"
$sudo lsof | grep myfile1.txt
OR
#ps -aux | grep tail

5)
Recover that file
$cp /proc/xxx/fd/4 myfile1.txt

* xxx is the PID of process which opened "myfile1.txt", this case it is "tail".