lsof的两个用法

一、查看端口占用情况

adam@hdn1:~$ sudo lsof -i :80
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2 1371     root    3u  IPv4  11004      0t0  TCP *:http (LISTEN)
apache2 1374 www-data    3u  IPv4  11004      0t0  TCP *:http (LISTEN)
apache2 1375 www-data    3u  IPv4  11004      0t0  TCP *:http (LISTEN)
apache2 1376 www-data    3u  IPv4  11004      0t0  TCP *:http (LISTEN)
apache2 1377 www-data    3u  IPv4  11004      0t0  TCP *:http (LISTEN)
apache2 1378 www-data    3u  IPv4  11004      0t0  TCP *:http (LISTEN)

2013-10-22增加:下面的netstat命令也能起到同样的作用

netstat -tlnp

二、在文件打开的情况下,恢复误删除的文件

adam@hdn1:~$ less test.txt
hello, this machine is called hdn1
this line is added by scp command on host hnn

test.txt (END)

打开另外一个shell环境

adam@hdn1:~$ rm test.txt
adam@hdn1:~$ ll test.txt
ls: cannot access test.txt: No such file or directory

可以看出test.txt文件已经不存在了。

adam@hdn1:~$ lsof | grep test.txt
less      1698       adam    4r      REG    8,1       82  663692 /home/adam/test.txt (deleted)
adam@hdn1:~$ cat /proc/1698/fd/4
hello, this machine is called hdn1
this line is added by scp command on host hnn

从上面lsof命令输出结果可以看出,less命令在打开test.txt文件,且文件已经被删除。
使用下面的命令可以恢复被删除的test.txt文件。

adam@hdn1:~$ cat /proc/1698/fd/4 > test.txt
adam@hdn1:~$ cat test.txt
hello, this machine is called hdn1
this line is added by scp command on host hnn

参考资料:
Unix调试的瑞士军刀:lsof

Comments are closed.