//GetProcess.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class GetProcess {
public void executeCommand(String[] cmd){
Process proc = null;
try {
proc = Runtime.getRuntime().exec(cmd);
InputStream is = proc.getInputStream();
StreamGobbler localGob = new StreamGobbler(is);
new Thread(localGob).start();
Thread.sleep(1000);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
if (proc != null){
proc.destroy();
}
}
}
public static void main(String[] args) {
GetProcess test = new GetProcess();
String cmd = "ps -ef| grep java | awk '{print $2}'";
test.executeCommand(new String[]{"sh", "-c", cmd});
}
}
class StreamGobbler implements Runnable {
InputStream is;
public StreamGobbler(InputStream is){
this.is = is;
}
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line= "";
try {
while ((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
java执行Linux bash命令
最新推荐文章于 2024-06-04 23:38:02 发布