lsof linux
lsof list open files
Linux一切皆文件,通过文件不仅可以访问常规数据,还可以访问网络连接(套接字)和硬件,该文件描述符为应用程序与os之间提供了接口.lsof需访问各种特权文件,故需root运行
COMMAND contains the first nine characters of the name of the UNIX command associated with the process. 默认只显示前9个字符
PID is the Process IDentification number of the process.
TID is the task (thread) IDentification number, if task (thread) reporting is supported by the dialect and a task (thread) is being listed.
FD is the File Descriptor number of the file or:
- cwd current working directory
- mem memory mapped file
- rtd root directory
- txt program text (code and data)
FD is followed by one of these characters, describing the mode under which the file is open:
- r for read access
- w for write access
- u for read and write access
- space if mode unknow and no lock
TYPE is the type of the node associated with the file
- IPv4 IPv4 socket
- IPv6 an open IPv6 network file - even if its address is IPv4, mapped in an IPv6 address
- unix UNIX domain socket
- DIR directory
- FIFO FIFO special file
- DEL a linux map file that has been deleted
- CHR a charater special file 字符设备文件
- BLK a block special file 块设备文件
- SOCK a socket of unknown domain
- REG regular file
lsof常用用法
- -u 后面可跟uid 用户名 前面加^表示取反
lsof -u polkitd
lsof -u ^polkitd
lsof -u 81lsof -u ^81
- lsof -i 用来查看套接字文件
lsof -i 所有套接字的连接
lsof -i tcp
lsof -i udp
lsof -i :80
lsof -i tcp:80
lsof -U Unix socket Unix域套接字有个特殊用法可以显示到某个远程主机特点端口的连接
- -n 不做反解
- -r n repeat every n seconds
- -d select by FD set
lsof -d 22
lsof -d 24-25lsof -d 30,33
- -g select by gid
lsof -g 0 查看gid为0的所有组内成员打开的文件
lsof -g ^0 exclude gid 0 - lsof -N
select NFS files - lsof -i -a -u root 列出所有root用户的sockets文件
支持-a做and逻辑运算 - lsof -p select by pid
- lsof -u select by uid
lsof -u ^postfix - lsof -c select by command
列出以post开头程序打开的文件
lsof -c ^post - lsof +D /path/to/dir
递归列出打开对应dir下所有文件的进程,必须是目录
lsof 可以用来恢复特定情况下被删除的文件,当进程打开了某个文件,在/proc/PID/fd中即建立相应的文件描述符与此文件关联,在文件系统中将此文件删除,删除了文件系统目录索引,但是文件仍然存在于磁盘,进程并不知道文件被删除,仍然可以向对应的fd读取或写入,但是此文件在fs中已经无法找到,/proc挂载的是内存中所映射的一块区域,所以fd关联的文件其实位于内存中,当对fd进行读取或写入,是与内存进行交互,lsof即是访问/proc目录的文件描述符抽取信息.
当系统的某个文件被意外删除,如果还有进程在访问此文件,那就可以利用对应的fd恢复相应内容,
上面为对应的操作流程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律