Process

為什麼 pidof 不起作用?

  • December 5, 2021

在 的輸出中ps aux,我可以看到這個過程很好:

# ps aux | grep diff
root      7787 28.7  0.0   9368  4516 pts/3    D+   13:56  20:33 diff -qr mnt/mnt/md/ mnt/mnt2/
root     13130  0.0  0.0   6144   876 pts/4    S+   15:07   0:00 grep diff

pidof聲稱無法找到任何東西:

# pidof diff
# echo $?
1

查看手冊頁,沒有關於失去程序時該怎麼做的資訊,pidof 有。/proc/7787/exe是一個符號連結/usr/bin/diff/usr/bin/diff它本身是一個正常文件和一個 ELF。根據手冊頁,這應該匹配。

在 sysvinit 2.96 及更高版本中,pidof -z將包括處於磁碟 I/O (‘D’) 或殭屍 (‘Z’) 狀態的程序。

經過一些調查strace,似乎pidof也檢查了程序的狀態。我的diff程序D大部分時間都處於狀態,這意味著它正在等待 I/O 很多。有了這些知識,我跑pidof了很多次(大約在 3 秒內):

# pidof diff
7787
# pidof diff
# pidof diff
7787
# pidof diff
# pidof diff
# pidof diff
# pidof diff
# pidof diff
# pidof diff
# pidof diff
# pidof diff
# pidof diff
# pidof diff
7787
# pidof diff
7787

它確實“有時”返回它,似乎證實了pidof只返回未處於D狀態的程序的懷疑。

檢查pidofin的原始碼src/killall5.c(使用 獲得apt source sysvinit-utils),答案在第 599 行:

if ( (strchr(process_status, 'D') != NULL) ||
    (strchr(process_status, 'Z') != NULL) ){
  /* Ignore zombie processes or processes in
     disk sleep, as attempts
     to access the stats of these will
     sometimes fail. */

引用自:https://unix.stackexchange.com/questions/518411