Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting PID for a process using Groovy

Tags:

groovy

I'm trying to create a method in Groovy to get the Process ID of an application. I'm currently at this stage:

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()
}

But this gives me:

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

It looks like it's struggling on the awk command, but I can't seem to figure out where I'm going wrong. Any ideas?

like image 897
Fifer Sheep Avatar asked Jan 26 '15 23:01

Fifer Sheep


2 Answers

An alternative (as the output from ps shouldn't block any buffers)

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

println getPid('groovyconsole')
like image 142
tim_yates Avatar answered Oct 29 '22 16:10

tim_yates


on linux/bsd/... pgrep would make finding a running process alot easier. 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
like image 41
cfrick Avatar answered Oct 29 '22 17:10

cfrick