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

瘦欲@ 提交于 2019-12-22 01:08:02

问题


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?


回答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
}

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.



来源:https://stackoverflow.com/questions/16823666/getting-the-process-id-of-another-program-in-groovy-using-command-slinging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!