lsof

TL;DR

# Find the processes that have a given file open:
$ lsof path/to/file

# Find the process that opened a local internet port:
$ lsof -i :port

# Only output the process ID (PID):
$ lsof -t path/to/file

# List files opened by the given user:
$ lsof -u username

# List files opened by the given command or process:
$ lsof -c process_or_command_name

# List files opened by a specific process, given its PID:
$ lsof -p PID

# List open files in a directory:
$ lsof +D path/to/directory

# Find the process that is listening on a local IPv6 TCP port and don't convert network or port numbers:
$ lsof -i6TCP:port -sTCP:LISTEN -n -P

# MacOS 查看监听的端口
$ lsof -nP -i TCP -s TCP:LISTEN
$ lsof -nP -i UDP

# MacOS 查看监听端口的进程
$ lsof -i tcp:6379
$ lsof -i :2380

# MacOS 查看进程监听的端口
$ lsof -nP -p 891 | grep LISTEN