用 lsof 查出占用端口的进程

应用报「端口已被占用」、开发服务器起不来?一条命令找出是谁占着端口。

macOS进程端口lsof 文件占用诊断低风险
运行 lsof -nP -iTCP:8080 -sTCP:LISTEN,列出监听 8080 端口的进程(含 PID 和名称);把 8080 换成任意端口。

01命令

命令
$ lsof -nP -iTCP:8080 -sTCP:LISTEN

02作用说明

lsof 把打开的文件映射到进程,而 macOS 上套接字也是文件——所以 -iTCP:8080 选中该端口上的所有连接,-sTCP:LISTEN 进一步只保留正在监听的服务。-n 跳过 DNS 解析、-P 直接显示数字端口,输出即时。查到的 PID 传给 kill 即可释放端口。

03风险

风险低风险
!注意: 查询是只读的,但 kill 不是——先看清进程名;系统服务占用的端口(如 5353 的 mDNSResponder)不要杀。

04撤销

撤销
$ kill <PID from output>

05来源

  • lsof(8) man page
    manpagez.com · technical · 2026-09-17
    依据: The lsof man page documents the -iTCP address specification and the -sTCP:LISTEN state filter that selects only processes listening on the port.
  • lsof - List Open Files
    SS64 · technical · 2026-09-17
    依据: Documents the -i option in the form [46][protocol][@host][:port] to list network connections by TCP port and protocol, plus -n (no name resolution) and -P (numeric ports).

最后验证: 2026-09-19 · 分类: 网络

06相关方案