使用Groovy获取进程的PID
我试图在Groovy中创建一个方法来获取应用程序的进程ID。我目前处于这个阶段:使用Groovy获取进程的PID,groovy,Groovy,我试图在Groovy中创建一个方法来获取应用程序的进程ID。我目前处于这个阶段: String getProcessIdFor(String program) { def buffer = new StringBuffer() Process commandOne = 'ps -A'.execute() Process commandTwo = "grep -m1 '${program}'".execute() Process commandThree = "a
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$3.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$3.run(ProcessGroovyMethods.java:399)
... 1 more
Process finished with exit code 0
线程“thread-1”groovy.lang.GroovyRuntimeException中的异常:读取进程流时发生异常
awk:源代码第1行出现语法错误
位于org.codehaus.groovy.runtime.ProcessGroovyMethods$3.run(ProcessGroovyMethods.java:402)
上下文是
运行(Thread.java:745)
>>>“在linux/bsd/
pgrep
将使查找正在运行的进程变得更加容易。e、 g
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
的输出不应阻塞任何缓冲区)
'awk{print\$1}.execute()
有效吗?我只是使用findAll和split,而不是三个进程之间的管道。或者['awk',{print$1}].execute()
?在这个链接中有一些很好的解决方案,其中一些与平台无关--@Rao在那篇文章中,所有的答案都是关于获取JVM pid等的。,但我需要的是一个方法,它可以通过为进程获取字符串来检查任何进程的pidname@tim_yates那恐怕不行-同样的错误。这工作很有魅力-谢谢!!你正式列入我的英雄名单^_^
Integer getPid(processName) {
'ps -A'.execute()
.text
.split('\n')
.find { it.contains processName }?.split()?.first() as Integer
}
println getPid('groovyconsole')