【问题标题】:adb: Find PID from the adb shelladb:从 adb shell 中查找 PID
【发布时间】:2026-01-20 08:00:01
【问题描述】:

我正在尝试获取进程 INSIDE adb shell 的 PID。所以,我正在做 adb shell,它让我进入了 android shell。现在,如果我要使用常规 shell 获取 PID,我会使用

adb shell ps | grep android.process.acore | sed 's/\s\s*/ /g' | cut -d ' ' -f 2

adb shell ps | grep android.process.acore | awk '{ print $2 }'

我得到了 PID(一个数字 - ps | grep android.process.acore 的第二个字段)输出。

但是,如果我在 android shell 中运行上述命令(在执行 adb shell 之后),我将分别得到 /system/bin/sh: sed: not found/system/bin/sh: awk: not found 错误。这意味着,这些命令在 adb shell 中不可用。但是,grep 有效。

adb shell 内的ps | grep android.process.acore 的输出是:

XXX_x21   11826 441   502296 39028 ffffffff 4010ff6c S android.process.acore

我正在寻找号码 11826。 如何在adb shell 中提取它?

另外,如果有直接的方法可以在 adb shell 中获取 PID,请提供帮助。

问候, 反刍

【问题讨论】:

  • 您是否安装了busybox

标签: android linux bash shell adb


【解决方案1】:

从 6.0 开始的 Android 版本已经包含 pidof 实用程序:

usage: pidof [-s] [-o omitpid[,omitpid...]] [NAME]...

Print the PIDs of all processes with the given names.

-s      single shot, only return one pid.
-o      omit PID(s)

【讨论】:

  • 这是正确答案。 adb shell pidof com.yourapp
【解决方案2】:

不确定是否可以直接获取 PID,但是您可以尝试以下方法

设置`ps |grep android.process.acore` 回声 $2

这具有将 ps 命令的输出设置为变量 $1、$2、$3 等的效果。PID 值在 $2 中

【讨论】:

  • 您好史蒂夫,谢谢您的回答。但是,我被困在通过 java runexec() 使用 adb shell 中的命令。在此处查看详细信息:*.com/questions/21321085/… 任何帮助表示赞赏。问候,
【解决方案3】:

我试过这个,它似乎工作:

adb shell "set "ps | grep android.process.media"; kill -9 $2"

【讨论】:

    【解决方案4】:

    我试过这个,它似乎工作:

    1.adb shell -> ps -A | grep "android.process.acore"

    【讨论】:

      【解决方案5】:
      adb shell pidof [package name]
      

      adb shell pidof -s [package name]
      

      -s 选项用于单发,只返回一个 pid。

      【讨论】: