Java Runtime的使用详解
作者:fenglllle 发布时间:2021-10-23 06:46:39
前言
最近做项目框架,需要在框架结束的时候,关闭服务器连接,清除部分框架运行lock文件,这里就想到了shutdownhook,顺便学了学Runtime的使用
1. shutdownhook
demo示例,证明在程序正常结束的时候会调用,如果kill -9 那肯定就不会调用了
public class ShutdownHookTest {
public static void main(String[] args) {
System.out.println("==============application start================");
Runtime.getRuntime().addShutdownHook(new Thread(()->{
System.out.println("--------------hook 1----------------");
}));
Runtime.getRuntime().addShutdownHook(new Thread(()->{
System.out.println("--------------hook 2----------------");
}));
System.out.println("==============application end================");
}
}
正常运行结束,结果如下
==============application start================
==============application end================
--------------hook 1----------------
--------------hook 2----------------
Process finished with exit code 0
如果暂停,点击下图左下角的正方形红图标,停止正在运行的应用
结果如下,shutdownhook已执行。
shutdownhook可以处理程序正常结束的时候,删除文件,关闭连接等
2. exec执行
2.1 常规命令执行
demo示例如下,比如ls
public class ShutdownHookTest {
public static void main(String[] args) throws InterruptedException, IOException {
Process process = Runtime.getRuntime().exec("ls");
try (InputStream fis = process.getInputStream();
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
结果如下
而正常执行结果
但是这个方法有远程执行风险,即在浏览器端通过这个方法执行特定指令,比如执行rm -rf *,结果就很……
2.2 管道符
但是遇见管道符之后就会失效,什么办法解决,sh -c,但是不能直接用,否则获取到的是TTY窗口信息
public static void main(String[] args) throws IOException {
Process process = Runtime.getRuntime().exec("sh -c ps aux|grep java");
try (InputStream fis = process.getInputStream();
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
结果😓
sh -c的参数要分离,不然runtime会认为是一个参数
2.3源码分析
跟踪代码,使用ProcessImpl来执行指令
public Process exec(String[] cmdarray, String[] envp, File dir)
throws IOException {
return new ProcessBuilder(cmdarray)
.environment(envp)
.directory(dir)
.start();
}
ProcessBuilder
// Only for use by ProcessBuilder.start()
static Process start(String[] cmdarray,
java.util.Map<String,String> environment,
String dir,
ProcessBuilder.Redirect[] redirects,
boolean redirectErrorStream)
throws IOException
{
assert cmdarray != null && cmdarray.length > 0;
// Convert arguments to a contiguous block; it's easier to do
// memory management in Java than in C.
byte[][] args = new byte[cmdarray.length-1][];
int size = args.length; // For added NUL bytes
for (int i = 0; i < args.length; i++) {
args[i] = cmdarray[i+1].getBytes();
size += args[i].length;
}
byte[] argBlock = new byte[size];
int i = 0;
for (byte[] arg : args) {
System.arraycopy(arg, 0, argBlock, i, arg.length);
i += arg.length + 1;
// No need to write NUL bytes explicitly
}
int[] envc = new int[1];
byte[] envBlock = ProcessEnvironment.toEnvironmentBlock(environment, envc);
int[] std_fds;
FileInputStream f0 = null;
FileOutputStream f1 = null;
FileOutputStream f2 = null;
try {
if (redirects == null) {
std_fds = new int[] { -1, -1, -1 };
} else {
std_fds = new int[3];
if (redirects[0] == Redirect.PIPE)
std_fds[0] = -1;
else if (redirects[0] == Redirect.INHERIT)
std_fds[0] = 0;
else {
f0 = new FileInputStream(redirects[0].file());
std_fds[0] = fdAccess.get(f0.getFD());
}
if (redirects[1] == Redirect.PIPE)
std_fds[1] = -1;
else if (redirects[1] == Redirect.INHERIT)
std_fds[1] = 1;
else {
f1 = new FileOutputStream(redirects[1].file(),
redirects[1].append());
std_fds[1] = fdAccess.get(f1.getFD());
}
if (redirects[2] == Redirect.PIPE)
std_fds[2] = -1;
else if (redirects[2] == Redirect.INHERIT)
std_fds[2] = 2;
else {
f2 = new FileOutputStream(redirects[2].file(),
redirects[2].append());
std_fds[2] = fdAccess.get(f2.getFD());
}
}
return new UNIXProcess
(toCString(cmdarray[0]),
argBlock, args.length,
envBlock, envc[0],
toCString(dir),
std_fds,
redirectErrorStream);
} finally {
// In theory, close() can throw IOException
// (although it is rather unlikely to happen here)
try { if (f0 != null) f0.close(); }
finally {
try { if (f1 != null) f1.close(); }
finally { if (f2 != null) f2.close(); }
}
}
}
new UNIXProcess 环境
/**
* java.lang.Process subclass in the UNIX environment.
*
* @author Mario Wolczko and Ross Knippel.
* @author Konstantin Kladko (ported to Linux and Bsd)
* @author Martin Buchholz
* @author Volker Simonis (ported to AIX)
*/
final class UNIXProcess extends Process {
3. 总结
Runtime用处非常多,偏底层
比如gc调用
加载jar文件
Runtime功能强大,但需要合理利用,很多攻击是通过Runtime执行的漏洞
但是使用shutdownhook还是很方便的,用来做停止任务的后续处理。
来源:https://blog.csdn.net/fenglllle/article/details/89525533
猜你喜欢
- 分页是Java Web项目常用的功能,昨天在Spring MVC中实现了简单的分页操作和搜索分页,在此记录一下。使用的框架为(MyBatis
- 前几天工作中一段业务代码需要一个变量每天从1开始递增。为此自己简单的封装了一个线程安全的计数器,可以让一个变量每天从1开始递增。当然了,如果
- 一、背景上一篇通过Java自带的JConsole来获取zookeeper状态。主要有几个不方便的地方,zk集群一般会部署3或者5台,在多个J
- 一、SpringBoot整合FastJson1.1、引入FastJson依赖包maven项目:<dependency> &nbs
- 本文实例为大家分享了java排序算法之冒泡排序的具体代码,供大家参考,具体内容如下冒泡排序冒泡排序无疑是最为出名的排序算法之一,从序列的一端
- 本文实例为大家分享了Java实现颜色渐变效果的具体代码,供大家参考,具体内容如下RGB色彩,在自然界中肉眼所能看到的任何色彩都可以由红(R)
- openid可以标识一个用户,session_key会变,所以来获取一下openid。openid不能在微信小程序中直接获取,需要后台发送请
- 在实际项目当中,我们经常会涉及到对时间的处理,例如登陆网站,我们会看到网站首页显示XXX,欢迎您!今天是XXXX年。。。。某些网站会记录下用
- Springboot整合RockerMQ1、maven依赖<dependencies> <!--
- SpringBoot @NotBlank错误java 验证出现如下错误:javax.validation.UnexpectedTypeExc
- 异常的英文单词是exception,字面翻译就是“意外、例外”的意思,也就是非正常情况。事实上,异常本质上是程序上的错误,包括程序逻辑错误和
- 简介Springboot Admin是一个管理和监控Springboot项目的组件,分为服务端和客户端,两端通过http进行通信。由于其轻量
- 简介我们知道Java中Collection接口下的很多集合都是线程不安全的, 比如 java.util.ArrayList不是线程安全的,
- 整合Spring Data JPAJPA (Java Persistence API)和 Spring Data 是两个范畴的概念。Hibe
- 前言由于刚写项目不久,在写 web 后台接口时,经常会对前端传入的参数进行一些规则校验,如果入参较少还好,一旦需要校验的参数比较多,那么使用
- 本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序的数据缓存功能。在Spring Boot应用程序中,我们可
- 一般而言,一个项目部署的由:拉取代码->构建->测试->打包->部署等过程组成,如果我们经常需要部署项目,特别是在微
- 前言本文主要跟大家介绍了关于Java用gson解析Json的相关内容,分享出来供大家参考学习,需要的朋友们下面来一起看看吧。json数据{&
- 转发和重定向相同点都是web开发中资源跳转的方式。不同点转发:是服务器内部的跳转,浏览器的地址栏不会发生变化。从一个页面到另一个页面的跳转还
- 一个项目中需要使用两个数据库,Oracle 和Mysql,于是参考各个blog,实现此功能。写好后才发现,原来的事务失效了,我去...spr