[Linux] 使用 lsof, lslocks, fuser 指令列出目前鎖定中的 file locks

[Linux] 使用 lsof, lslocks, fuser 指令列出目前鎖定中的 file locks

在 Linux 上面,要列出目前鎖定中的 file lock,我通常是用 lsof 來找,例如:

testuser@localhost ~ $ lsof -n 2>/dev/null | egrep "W.*sublime-text"
subl      16323        testuser  117uW  REG  253,2  0 1081735587 /home/testuser/.config/sublime-text-3/Index/LOCK
gdbus     16323 16328  testuser  117uW  REG  253,2  0 1081735587 /home/testuser/.config/sublime-text-3/Index/LOCK
thread_qu 16323 16329  testuser  117uW  REG  253,2  0 1081735587 /home/testuser/.config/sublime-text-3/Index/LOCK
io_worker 16323 16330  testuser  117uW  REG  253,2  0 1081735587 /home/testuser/.config/sublime-text-3/Index/LOCK
io_worker 16323 16331  testuser  117uW  REG  253,2  0 1081735587 /home/testuser/.config/sublime-text-3/Index/LOCK
gmain     16323 16332  testuser  117uW  REG  253,2  0 1081735587 /home/testuser/.config/sublime-text-3/Index/LOCK
shm_reade 16323 16338  testuser  117uW  REG  253,2  0 1081735587 /home/testuser/.config/sublime-text-3/Index/LOCK
process_s 16323 16340  testuser  117uW  REG  253,2  0 1081735587 /home/testuser/.config/sublime-text-3/Index/LOCK
subl      16323 16349  testuser  117uW  REG  253,2  0 1081735587 /home/testuser/.config/sublime-text-3/Index/LOCK

 

lsof 的缺點是因為要列出目前系統中所有開啟的檔案,所以要稍微等一下,

也得用 grep 來找自己關注的檔案,目前是哪個 process 鎖住了 file lock 也得找 W 屬性的,

但好處是其他在等這個 file lock 的 process 也可以同時列出來 (w 屬性)~

 

今天在查一個東西的時候,才發現除了 lsof 以外,還有其他好用的指令可以用~

像是用 lslocks 就可以直接把目前鎖住 lock 的 process 列出來:

testuser@localhost ~ $ lslocks | egrep sublime-text
subl   16323 POSIX   0B WRITE 0   0   0 /home/testuser/.config/sublime-text-3/Index/LOCK

 

如果有其他的 process 也在等這個 lock,那就會用 * 來代表,

例如下面的 python 32258 已經鎖住了 /tmp/cli_proc.lock 這個 file lock,

而 python 33461 正在等待這個 file lock 釋出:

python 33461 FLOCK  0B WRITE* 0  0  0 /tmp/cli_proc.lock
python 32258 FLOCK  0B WRITE  0  0  0 /tmp/cli_proc.lock

 

另外,也可以用 fuser 這個指令來列出目前開啟這個檔案的 process pid,

但缺點是看不出來哪一個 process 是目前鎖定 file lock 的:

testuser@localhost ~ $ fuser -u /home/testuser/.config/sublime-text-3/Index/LOCK
/home/testuser/.config/sublime-text-3/Index/LOCK: 16323(testuser)
testuser@localhost ~ $ ps aux | grep 16323
testuser 16323  0.0  0.5 1739384 167364 ?   Ssl  Feb23   1:36 subl

 

參考資料:How to list processes locking file?

 

(本頁面已被瀏覽過 3,428 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料