为什么 pidof 和 pgrep 的行为不同?

Pig*_*ras 9 grep process init-script pidof

我有一个 init 脚本/etc/init.d/myservice用于初始化这样的服务:

...
start() {
  ...
  daemon /usr/sbin/myservice
  ...
}

stop() {
  ...
  pgrep myservice
  pidof myservice
  ps -ef | grep myservice
  ...
}
Run Code Online (Sandbox Code Playgroud)

当我尝试停止服务时,这是输出:

10000 10001
10000
root      10000     1  0 09:52 ?        00:00:02 /usr/sbin/myservice
root      9791   9788  0 10:06 pts/1    00:00:00 /bin/sh /sbin/service myservice stop
root      10001  9791  1 10:06 pts/1    00:00:00 /bin/sh /etc/init.d/myservice stop 
root      9805   9796  0 10:06 pts/1    00:00:00 grep myservice
Run Code Online (Sandbox Code Playgroud)

这是预期的吗?为什么pidof只返回我想要停止的服务的正确 PID 并pgrep返回服务 PID 和 init 脚本的 PID?我可以依靠它pidof总是忽略 init 脚本中的 PID 吗?

Bab*_*ton 8

pidof = 查找正在运行的程序的进程 ID

Pidof 查找指定程序的进程 ID (pid)。它在标准输出上打印这些 id。这个程序在一些用于运行级更改脚本的系统上,特别是当系统具有类似 System-V 的 rc 结构时。

sysadmin@codewarden:~$ pidof apache2
5098 5095 5094 5092
Run Code Online (Sandbox Code Playgroud)

pgrep = 根据名称和其他属性查找或发送进程信号,pgrep 查看当前正在运行的进程并列出与选择标准匹配的进程 ID。

sysadmin@codewarden:~$ pgrep apache2
5092
5094
5095
5098
Run Code Online (Sandbox Code Playgroud)

pgrep, (p) = process, grep= grep 打印匹配的行

想了解更多关于 pgrep 和 pidof 的信息?只需在终端中运行

# man pidof
# man pgrep
Run Code Online (Sandbox Code Playgroud)