简体   繁体   English

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

[英]how to extract the PID of a process by command line

I want to get the PID of a process namely "cron" by command line. 我想通过命令行获取进程的PID,即“cron”。 I tried the following script. 我尝试了以下脚本。

ps ax|grep 'cron'

but I am getting a part of a table, 但是我得到了一张桌子的一部分,

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

How I extract the pid from this ? 我是如何从中提取pid的?

The pgrep utility will return the process IDs for the currently running processes matching its argument: pgrep实用程序将返回与其参数匹配的当前正在运行的进程的进程ID:

$ pgrep cron
228

It may also be used to "grep for" things on the command line: 它也可以用于命令行上的“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

To kill a process by name, use pkill . 要的名字来杀死一个过程,使用pkill It works in the same way as pgrep but will send a signal to the matched processes instead of outputting a process ID. 它的工作方式与pgrep相同,但会向匹配的进程发送信号,而不是输出进程ID。

Just use pidof , rather to use other commands and apply post-processing actions on them. 只需使用pidof ,而不是使用其他命令并对它们应用后处理操作。

$ pidof cron
22434

To make the command return only one PID pertaining to to the process, use the -s flag 要使命令仅返回与进程有关的一个PID ,请使用-s标志

-s Single shot - this instructs the program to only return one pid. -s单击 - 这指示程序只返回一个pid。

像这样,例如:

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

You can try this; 你可以试试这个;

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

or 要么

pstree -pas <cronPID>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM