ファイルを掴んでいるプロセスを調べる
lsof <ファイル名>
でファイルを使用しているプロセルを特定できる。
$ sudo lsof /var/log/messages COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME rsyslogd 1055 root 3w REG 253,0 7164 100839039 /var/log/messages
実行結果の4番目のフィールドが [0-9]w
なのは書き込みモード、[0-9]u
が読み書きモードで開かれているファイル。
応用として、書き込みモードで開かれているファイルの一覧取得方法。
$ sudo lsof|awk '$4~/^[0-9][wu][a-zA-Z]*$/{print $O}'
wとuの後には以下のようなロックモードがアルファベト1文字で表示されるので正規表現にその考慮を入れています。
The mode character is followed by one of these lock characters, describing the type of lock applied to the file: N for a Solaris NFS lock of unknown type; r for read lock on part of the file; R for a read lock on the entire file; w for a write lock on part of the file; W for a write lock on the entire file; u for a read and write lock of any length; U for a lock of unknown type; x for an SCO OpenServer Xenix lock on part of the file; X for an SCO OpenServer Xenix lock on the entire file; space if there is no lock.
または、/proc/<PID>/fd/
にプロセルが使用しているファイルへのシンボリックリンクが貼られているので、ls -l
で調べる方法もある。
$ ls -l /proc/5271/fd total 0 lrwx------. 1 vagrant vagrant 64 Jan 7 15:34 0 -> /dev/pts/0 lrwx------. 1 vagrant vagrant 64 Jan 7 15:34 1 -> /dev/pts/0 lrwx------. 1 vagrant vagrant 64 Jan 7 15:34 2 -> /dev/pts/0 lrwx------. 1 vagrant vagrant 64 Jan 7 15:34 4 -> /home/vagrant/.hoge.txt.swp
CentOS7で試したけど他のOSだと少し違うかも。