【问题标题】:Getting the Process ID of another program in Groovy using 'command slinging'使用“命令吊索”在 Groovy 中获取另一个程序的进程 ID
【发布时间】:2013-05-29 20:57:46
【问题描述】:
import java.lang.management.*

final String name = ManagementFactory.getRuntimeMXBean().getName();
final Integer pid = Integer.parseInt(name[0..name.indexOf("@")-1])

我在我的代码中尝试了这个,但它得到了正在运行的程序的 pid。我正在运行一个名为 sleep.sh 的睡眠脚本(它所做的只是睡眠),我想获得它的 pid。有没有办法做到这一点?我自己还没有找到一个很好的方法。

我也用了ps | grep 我可以看到进程 ID 有没有办法输出它?

Process proc1 = 'ps -ef'.execute()
Process proc2 = 'grep sleep.sh'.execute()
Process proc3 = 'grep -v grep'.execute()
all = proc1 | proc2 | proc3

有没有一种方法可以修改 all.text 以获取进程 ID,或者有其他方法可以获取它吗?

【问题讨论】:

  • nvm 我回答了。如果您想回答这个问题,仍然会给出最佳答案
  • 如果你有解决办法,下面totally acceptable回答并采纳!

标签: groovy scripting grep pid ps


【解决方案1】:
Object getNumber(String searchProc) {
        //adds the process in the method call to the grep command
        searchString = "grep "+searchProc

        // initializes the command and pipes them together
        Process proc1 = 'ps -ef'.execute()
        Process proc2 = searchString.execute()
        Process proc3 = 'grep -v grep'.execute()
        all = proc1 | proc2 | proc3

        //sets the output to the piped commands to a string
        output = all.text

        //trims down the string to just the process ID
        pid = output.substring(output.indexOf(' '), output.size()).trim()
        pid = pid.substring(0, pid.indexOf(' ')).trim()
        return pid
}

这是我的解决方案。 (我想把它变成一个方法,所以我把方法声明放在最上面) 一开始我的问题是进程名称和pid之间的空格多于一个。但后来我找到了修剪方法,效果很好。如果您对我的方法有任何疑问,请告诉我。我会定期回来查看。

【讨论】:

  • 另外,如果你想返回一个 int,你可以使用 toInteger 方法。 (例如 pid = pid.toInteger())
猜你喜欢
  • 2011-09-25
  • 1970-01-01
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
相关资源
最近更新 更多