使用 Groovy 获取进程的 PID

Getting PID for a process using Groovy

我正在尝试在 Groovy 中创建一个方法来获取应用程序的进程 ID。我目前处于这个阶段:

String getProcessIdFor(String program) {
    def buffer = new StringBuffer()

    Process commandOne = 'ps -A'.execute()
    Process commandTwo = "grep -m1 '${program}'".execute()
    Process commandThree = "awk '{print $1}'".execute()

    Process process = commandOne | commandTwo | commandThree
    process.waitForProcessOutput(buffer, buffer)

    return buffer.toString()
}

但这给了我:

Exception in thread "Thread-1" groovy.lang.GroovyRuntimeException: exception while reading process stream
awk: syntax error at source line 1
at org.codehaus.groovy.runtime.ProcessGroovyMethods.run(ProcessGroovyMethods.java:402)
context is
at java.lang.Thread.run(Thread.java:745)
 >>> ' <<< 
missing }
Caused by: java.io.IOException: Stream closed
awk: bailing out at source line 1
at java.lang.ProcessBuilder$NullOutputStream.write(ProcessBuilder.java:434)
at java.io.OutputStream.write(OutputStream.java:116)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:122)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:122)
at org.codehaus.groovy.runtime.ProcessGroovyMethods.run(ProcessGroovyMethods.java:399)
... 1 more

Process finished with exit code 0

看起来它在 awk 命令上挣扎,但我似乎无法弄清楚我哪里出错了。有什么想法吗?

on linux/bsd/... pgrep 将使查找 运行 进程变得容易得多。例如

def b = new StringBuffer()
def p = 'pgrep zsh'.execute() // does a zsh run?
p.waitForProcessOutput(b,b)
assert b // any output?  there is a zsh running
assert b.split().first().toInteger() > 0 // split, take first and cast to integer for the first pid returned

b = new StringBuffer()
p = 'pgrep nuffin'.execute() // use `-f` to use the "whole" command line
p.waitForProcessOutput(b,b)
assert !b // empty string?  process not running

替代方案(因为 ps 的输出不应阻塞任何缓冲区)

Integer getPid(processName) {
    'ps -A'.execute()
           .text
           .split('\n')
           .find { it.contains processName }?.split()?.first() as Integer
}

println getPid('groovyconsole')