首页 文章

如何根据进程名称获取pid

提问于
浏览
39

嗨我已经搜索了各种论坛,在这里,我可以找到Linux和Mac的一些答案,但无法找到Unix和特别是Korn Shell的解决方案 .

如何从进程ID(pid)获取进程名称(命令名称)

以下是我发现的SO This one And this one also

我试过下面的命令

ps -eaf | awk '{ print substr($0, index($0, $9)) }'

上面的命令在给定TIME而不是Month和Date的位置失败(因为在这种情况下,字符串中只有8列)

任何建议都会有所帮助 .

4 回答

  • 2

    我认为使用pgrep更容易

    $ pgrep bluetoothd
    441
    

    否则,您可以使用 awk

    ps -ef | awk '$8=="name_of_process" {print $2}'
    

    例如,如果 ps -ef 有一行如下:

    root       441     1  0 10:02 ?        00:00:00 /usr/sbin/bluetoothd
    

    然后 ps -ef | awk '$8=="/usr/sbin/bluetoothd" {print $2}' 返回 441 .


    在ksh中找不到pgrep . 另一个解决方案是失败,如果下面的情况是从ps命令输出jaggsmca325 7550 4752 0 Sep 11 pts / 44 0:00 sqlplus dummy_user / dummy_password @ dummy_schema

    让我们检查最后一栏( $NF ),无论其编号如何:

    $ ps -ef | awk '$NF=="/usr/sbin/bluetoothd" {print $2}'
    441
    

    如果要匹配不完全匹配的字符串,可以使用 ~ 代替:

    $ ps -ef | awk '$NF~"bluetooth" {print $2}'
    441
    1906
    
  • 66

    您可以使用 pidof 获取名称为 p_name 的正在运行的进程的所有ID
    pidof p_name | tr ' ' '\n' (垂直列表)
    pkill p_name 杀死名称为 p_name 的所有进程
    NB 确保你有权杀死他们:)

  • 5

    如果您的 ps | awk 解决方案失败,因为 ps 的输出不是您想要的,那么请执行以下操作:

    ps -eaf -o pid,cmd | awk '/regex-to-match-command-name/{ print $1 }'
    
  • 0
    ps -C <the-name> -o etime=
    

    我的ps来自procps-ng .

相关问题