lsof by example 例子

参考的原文地址:http://www.akadia.com/services/lsof_intro.html

Introduction to lsof


Overview

LiSt Open Files is a useful and powerful tool that will show you opened files. In Unix everything is a file: pipes are files, IP sockets are files, unix sockets are files, directories are files, devices are files, inodes are files...

Useful Examples

So in this tangle of files lsof listst files opened by processes running on your system.

When lsof is called without parameters, it will show all the files opened by any processes.

     lsof | nl

Let us know who is using the apache executable file, /etc/passwd, what files are opened on device /dev/hda6 or who's accessing /dev/cdrom: 这个不错,可以查出来一个文件正在被什么进程使用

     lsof `which apache2`
     lsof /etc/passwd
     lsof /dev/hda6
     lsof /dev/cdrom

Now show us what process IDs are using the apache binary, and only the PID:

     lsof -t `which apache2`

Show us what files are opened by processes whose names starts by "k" (klogd, kswapd...) and bash. Show us what files are opened by init:

     lsof -c k
     lsof -c bash
     lsof -c init

Show us what files are opened by processes whose names starts by "courier", but exclude those whose owner is the user "zahn":

     lsof -c courier -u ^zahn

Show us the processes opened by user apache and user zahn:

     lsof -u apache,zahn 查看某个用户使用的文件

Show us what files are using the process whose PID is 30297:

     lsof +p 30297 根据进程号查看他在使用的文件

Search for all opened instances of directory /tmp and all the files and directories it contains:

     lsof +D /tmp

List all opened internet sockets and sockets related to port 80:

     lsof -i
     lsof -i :80
很好,能查看端口的占用

List all opened Internet and UNIX domain files:

     lsof -i -U

Show us what process(es) has an UDP connection opened to or from the host www.akadia.com at port 123 (ntp):

     lsof -iUDP@www.akadia.com:123

lsof provides many more options and could be an unvaluable foresinc tool if your system get compromised or as daily basis check tool.

原文地址:https://www.cnblogs.com/welkinwalker/p/2249699.html