Process类是一个抽象类(所有的方法均是抽象的),封装了一个进程(即一个执行程序).
Process类提供了执行从进程输入、执行输出到进程、等待进程完成、检查进程的退出状态以及销毁(杀掉)进程的方法.
二、API预览
destroy()
杀掉子进程。
exitValue()
返回子进程的出口值。
InputStream getErrorStream()
获得子进程的错误流。
InputStream getInputStream()
获得子进程的输入流。
OutputStream getOutputStream()
获得子进程的输出流。
waitFor()
导致当前线程等待,如果必要,一直要等到由该 Process 对象表示的进程已经终止。
例子
(此例子是用脚本语言查询服务器Tcp连接数和新建连接数 详细请点击打开链接)
//-c参数是告诉它读取随后的字符串,而最后的参数是你要运行的脚本。
String[] commands = new String[] { "/bin/bash", "-c", "ss -na | awk '{print $1}' | sort | uniq -c" };
try {
Process process = Runtime.getRuntime().exec(commands);//执行命令
//process.waitFor();
//读取屏幕输出
BufferedReader strCon = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
int linkNow = 0;
int linkNew = 0;
while ((line = strCon.readLine()) != null) {
if (line.contains("ESTAB")) {
String values = line.substring(0, line.indexOf("ESTAB"));
linkNow = Integer.valueOf(values.trim());
} else if (line.contains("SYN") || line.toUpperCase().contains("SYN")) {
String values = line.substring(0, line.indexOf("SYN"));
linkNew = Integer.valueOf(values.trim());
} else if (line.contains("LISTEN")) {
String values = line.substring(0, line.indexOf("LISTEN"));
linkNew += Integer.valueOf(values.trim());
}
}
linkService.add(Constants.PORTAL_DEVICE_IP, linkNow, linkNew, now);
logger.info("<--- getLinkData(" + (System.currentTimeMillis() - begin) / 1000 + "s) --->");
strCon.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}