lsof
プロセスとシステム
書き方
lsof -i :<port>開いているファイルとソケットをすべて並べ、「3000 番ポートを誰が握っているか」に答えます。sudo なしでは自分のプロセスしか見えないので、結果が空でもポートが空いている証拠にはなりません。
よく使うオプション
| オプション | 意味 |
|---|---|
| -i :3000 | Which process holds port 3000, in either direction. |
| -i TCP -sTCP:LISTEN | Listening TCP sockets only. |
| -t | Print bare PIDs, made for piping into kill. |
| -p <pid> | Everything one process has open. |
| -u <user> | One user's open files. |
| +D <dir> | Every open file underneath a directory, recursively. |
| -n -P | Skip host and port name lookups, which makes it much faster. |
例
lsof -i :3000The classic answer to "something is already using port 3000".
kill -9 $(lsof -ti :3000)Kill whatever holds that port.
sudo lsof +D /var/logFind the process keeping a deleted log file open.
何が動いていて何が資源を食っているかを見ます。止める前に何なのかを確かめるのが順番です。
読み方
- 角括弧 [ ] は省いてよい部分です。
- 三点 … は複数並べられるという意味です。
- オプションは大文字小文字を区別します — -r と -R が別物のコマンドもあります。
よくある質問
Q. lsof は何をしますか。
開いているファイルとソケットをすべて並べ、「3000 番ポートを誰が握っているか」に答えます。sudo なしでは自分のプロセスしか見えないので、結果が空でもポートが空いている証拠にはなりません。
Q. どう打ちますか。
lsof -i :<port> — 角括弧は省いてよい部分です。
Q. よく使うオプションはいくつですか。
ここにまとめたのは7個です。全部は man lsof にあります。このコマンドはプロセスとシステムの仲間です。
関連するコマンド
man ページ: man lsof