2013-05-29 19 views
1
import java.lang.management.* 

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

我在我的代碼中試過這個,但是得到了正在運行的程序的pid。我正在運行一個睡眠腳本(它所做的就是睡眠),名爲sleep.sh,我希望獲得該腳本的pid。有沒有辦法做到這一點?我自己並沒有找到一個很好的方法。使用'command slinging'獲取Groovy中另一個程序的進程ID

我也用ps | grep,我可以看到進程ID有沒有辦法輸出它呢?

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

是我有辦法可以修改all.text獲得進程ID或有另一種方式得到它?

+0

nvm我回答了。如果你想回答這個問題,仍然會給出最好的答案 – Ian

+1

如果你有一個解決方案,它是[完全可以接受的](http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer - 你自己的問題/)在下面回答並接受它! – OverZealous

回答

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

這是我的解決方案。 (我想使它成爲一種方法,所以我把方法聲明放在最上面) 我的問題一開始是進程名稱和pid之間的空間多於一個。但後來我發現了修剪方法,並很好地工作。如果您對我的方法有疑問,請告訴我。我會定期檢查。

+1

另外,如果你想返回一個int,你可以做toInteger方法。 (例如,pid = pid.toInteger()) – Ian

相關問題