最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java?Runtime的使用詳解

 更新時間:2021年12月15日 15:04:15   作者:fenglllle  
這篇文章主要介紹了Java?Runtime的使用詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

前言

最近做項目框架,需要在框架結束的時候,關閉服務器連接,清除部分框架運行l(wèi)ock文件,這里就想到了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已執(zhí)行。

shutdownhook可以處理程序正常結束的時候,刪除文件,關閉連接等

2. exec執(zhí)行

2.1 常規(guī)命令執(zhí)行

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);
            }
        }
    }
}

結果如下

而正常執(zhí)行結果

但是這個方法有遠程執(zhí)行風險,即在瀏覽器端通過這個方法執(zhí)行特定指令,比如執(zhí)行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來執(zhí)行指令

    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 環(huán)境

 
/**
 * 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執(zhí)行的漏洞

但是使用shutdownhook還是很方便的,用來做停止任務的后續(xù)處理。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • j2ee mybatis注解@Data,@TableName,@TableField使用方式

    j2ee mybatis注解@Data,@TableName,@TableField使用方式

    這篇文章主要介紹了j2ee mybatis注解@Data,@TableName,@TableField使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • Java線程池的幾種實現(xiàn)方法及常見問題解答

    Java線程池的幾種實現(xiàn)方法及常見問題解答

    下面小編就為大家?guī)硪黄狫ava線程池的幾種實現(xiàn)方法及常見問題解答。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-05-05
  • 聊聊Java 成員變量賦值和構造方法誰先執(zhí)行的問題

    聊聊Java 成員變量賦值和構造方法誰先執(zhí)行的問題

    這篇文章主要介紹了聊聊Java 成員變量賦值和構造方法誰先執(zhí)行的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-10-10
  • 一文詳解Java中字符串的基本操作

    一文詳解Java中字符串的基本操作

    這篇文章主要為大家詳細介紹了Java中字符串的基本操作,例如遍歷、統(tǒng)計次數,拼接和反轉等以及String的常用方法,感興趣的可以了解一下
    2022-08-08
  • MyBatis批量插入大量數據(1w以上)

    MyBatis批量插入大量數據(1w以上)

    MyBatis進行批量插入數時,一次性插入超過一千條的時候MyBatis開始報錯,本文主要介紹了MyBatis批量插入大量數據的解決方法,感興趣的可以了解一下
    2022-01-01
  • Springboot源碼 TargetSource解析

    Springboot源碼 TargetSource解析

    這篇文章主要介紹了Springboot源碼 TargetSource解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-08-08
  • 基于IO版的用戶登錄注冊實例(Java)

    基于IO版的用戶登錄注冊實例(Java)

    下面小編就為大家?guī)硪黄贗O版的用戶登錄注冊實例(Java)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • Mybatis調用MySQL存儲過程的簡單實現(xiàn)

    Mybatis調用MySQL存儲過程的簡單實現(xiàn)

    本篇文章主要介紹了Mybatis調用MySQL存儲過程的簡單實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-04-04
  • java實現(xiàn)圖形化界面計算器

    java實現(xiàn)圖形化界面計算器

    這篇文章主要為大家詳細介紹了java實現(xiàn)圖形化界面計算器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-05-05
  • java中public class與class的區(qū)別詳解

    java中public class與class的區(qū)別詳解

    以下是對java中public class與class的區(qū)別進行了分析介紹,需要的朋友可以過來參考下
    2013-07-07

最新評論

法库县| 佛学| 宜都市| 定安县| 天气| 武山县| 漳平市| 宁阳县| 海城市| 阳朔县| 泌阳县| 岳西县| 民勤县| 漯河市| 元江| 屯门区| 义马市| 三穗县| 运城市| 锦屏县| 临泽县| 浙江省| 渑池县| 叙永县| 麻阳| 武平县| 吉安县| 慈利县| 毕节市| 花莲县| 高阳县| 宁晋县| 紫云| 延边| 金昌市| 雅江县| 沂源县| 怀宁县| 成安县| 永平县| 郯城县|