Search code examples
groovyscriptinggreppidps

Getting the Process ID of another program in Groovy using 'command slinging'


import java.lang.management.*

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

I tried this in my code but that gets the pid of the running program. I am running a sleeping script (all it does is sleep) called sleep.sh and i want to get the pid of that. Is there a way to do that? I have not found a very good way myself.

I also used a ps | grep and i can see the process id is there a way to output it though?

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

is there a way i can modify the all.text to get the process id or is there another way to get it?


Solution

  • 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
    }
    

    This is my solution. (I wanted to make it a method so i put the method declaration at the very top) My problem at the beginning was that there was more spaces than one between the process name and the pid. but then i found the trim method and that worked nicely. If you have questions on my method let me know. I will check back periodically.