【问题标题】:How to get the PID from PS command output in Android shell如何从 Android shell 中的 PS 命令输出中获取 PID
【发布时间】:2013-02-09 21:46:15
【问题描述】:

谁能告诉我如何从 Android shell 中 PS 命令的输出中获取 PID。 例如从输出:

u0_a51    20240 38    132944 22300 ffffffff 40037ebc S com.example.poc_service

pid 值20240 将被获取。我试过了

ps -ef | grep com.example.poc_service

但无济于事。也无法识别pgrep

【问题讨论】:

  • 什么是“关键字”,即您在 ps 输出中搜索什么? (很容易隔离PID列,我会选择ps | awk '{print $2}'
  • 感谢安东的回复。但它会抛出错误** awk not found..** 似乎 Android shell 不支持所有的 linux 命令
  • 试试ps -C com.example.poc_service -o pid=(注意大写-C。不,我不确定它是否有效)
  • 这也不起作用:(
  • 虽然我的解决方案未被接受,但您可以在此处查看答案:stackoverflow.com/questions/8625212/…

标签: android shell


【解决方案1】:

如果你在 Android 中有 shell 访问权限,你也可以使用 pidof:

# pidof com.example.poc_service
20240 

但是,请注意,因为可能有多个进程匹配...

【讨论】:

  • 这看起来很有希望,但是当我运行它时,我得到了一堆 pid,从“1 2 3 6...”开始。有什么线索吗?
  • @JohannesBrodwall 你有什么替代品吗?
  • @JohannesBrodwall 可能是因为该进程在多个线程上运行。也可能是它启动了一堆子流程。
【解决方案2】:

它很讨厌,但它有效:

for pid in `ls /proc`; do 
   cmd=`cat $pid/cmdline 2> /dev/null`;

   if [ "X$cmd" == "Xcom.example.poc_service" ]; then
       echo $pid;
   fi 
done

或一行:

for pid in `ls /proc`; do cmd=`cat $pid/cmdline 2> /dev/null`; if [ "X$cmd" == "X/system/bin/mm-qcamera-daemon" ]; then echo $pid; fi done

【讨论】:

  • 不错的解决方案。在 echo $pid 之后添加一个中断;不过会提高效率。
【解决方案3】:

grepegrepfgreprgrep 在 Android 中均不可用。

如果您正在处理UnixLinuxMacCygwin,您可以通过管道输出adb shell 命令以获得您想要的结果。

$ adb shell ps |grep settings
system    23846 71    111996 22676 ffffffff 00000000 S com.android.settings
$ adb shell ps |grep settings |awk '{print $2}'
23846

【讨论】:

    猜你喜欢
    • 2013-07-29
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2018-03-18
    • 1970-01-01
    • 2012-02-07
    相关资源
    最近更新 更多