Process类Api
- public abstract OutputStream getOutputStream(); 获取输出流
- public abstract InputStream getInputStream(); 获取输入流
- public abstract InputStream getErrorStream(); 获取错误输入流
- public abstract int waitFor(); 阻塞父进程直到子进程退出
- public boolean waitFor(long var1, TimeUnit var3) throws InterruptedException; var3(时间)后退出进程
- public abstract int exitValue(); 退出当前进程
- public abstract void destroy(); 杀掉子进程
- public Process destroyForcibly(); 强行杀掉子进程
- public boolean isAlive(); 判断子进程是否处理运行状态
shell执行操作
package com.jipf.springboot.test;
import java.io.*;
import java.util.concurrent.*;
public class ShellExec {
public static void exec(String shell,long timeout){
try {
Process process = Runtime.getRuntime().exec(shell);
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<String> future1 = executorService.submit(()->{return handlerProcessBlock(process.getInputStream());});
Future<String> future2 = executorService.submit(()->{return handlerProcessBlock(process.getErrorStream());});
executorService.shoudown();
if (process.waitFor(timeout, TimeUnit.MILLISECONDS)){
if (process.exitValue() != 0){
System.out.println(future2.get());
}
}else {
System.out.println("exec time out!");
executorService.shoudownNow();
os.close();
process.destroy();
}
}catch (IOException e){
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
private static String handlerProcessBlock(InputStream inputStream){
BufferedReader reader = null;
try {
StringBuffer sb = new StringBuffer();
String buff;
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((buff = reader.readLine()) != null) {
sb.append(buff.trim()).append("\n");
}
return sb.toString();
}catch (IOException e){
e.printStackTrace();
}finally {
if (reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
public static void main(String[] args) {
exec("ls /opt",1000);
}
}