如何通过命令行提取进程的PID

时间:2016-07-28 11:06:21

标签: bash shell

我想得到一个过程的PID,即" cron"通过命令行。 我尝试了以下脚本。

ps ax|grep 'cron'

但是我得到了一张桌子的一部分,

   1427 ?        Ss     0:00 /usr/sbin/cron -f
24160 pts/5    S+     0:00 grep --color=auto cron

我如何从中提取pid?

4 个答案:

答案 0 :(得分:3)

只需使用pidof,而不是使用其他命令并对其应用后处理操作。

$ pidof cron
22434

要使命令只返回与进程相关的一个PID,请使用-s标志

  

-s   单发 - 这指示程序只返回一个pid。

答案 1 :(得分:3)

pgrep实用程序将返回与其参数匹配的当前正在运行的进程的进程ID:

$ pgrep cron
228

它也可能用于" grep for"命令行上的东西:

$ pgrep -f uerfale
69749
69752

$ pgrep -l -f uerfale
69749 slogin uerfale
69752 slogin: /home/kk/.ssh/sockets/uerfale-9022-kk.sock [mux] m

要按名称​​终止流程,请使用pkill。它的工作方式与pgrep相同,但会向匹配的进程发送信号,而不是输出进程ID。

答案 2 :(得分:1)

像这样,例如:

ps -ef|grep 'cron'|grep -v grep|awk '{print $2}'

答案 3 :(得分:1)

你可以试试这个;

ps -o pid,sess,cmd afx | egrep "( |/)cron( -f)?$"

pstree -pas <cronPID>
相关问题