繁体   English   中英

完成 Runtime.getRuntime().exec() 方法后杀死 Java 进程

[英]Kill Java Process after Completing Runtime.getRuntime().exec() method

我正在使用Runtime.getRuntime().exec()linux环境中执行shell脚本,但我看到 java 进程在完成此任务后没有终止。 完成此任务后如何停止/终止java 进程。

爪哇

private class Task implements Runnable{

        @Override
        public void run() {
            try {
                        Process process = Runtime.getRuntime().exec(new String[]{shellfile}, null, new File(shellfilepath));
                    }
            } catch (IOException e) {

        };

    }

你有几个选择。 您可以使用Process#waitFor阻塞直到任务完成

class Task implements Runnable{
    @Override
    public void run() {
        try {
            final Process process = Runtime.getRuntime().exec(new String[]{shellfile}, null, new File(shellfilepath));
            process.waitFor();
        } catch (final IOException | InterruptedException e) {
            // handle the error
        }
    };
}

如果您认为程序可能挂起,您可以将waitFor包装在一个Threadjoin超时。 超时后,您可以对进程调用destroy

class Task implements Runnable{
    @Override
    public void run() {
        try {
            final Process process = Runtime.getRuntime().exec(new String[]{shellfile}, null, new File(shellfilepath));
            final Thread thread = new Thread(process::waitFor);
            thread.start();
            thread.join(1000);
            process.destroy();
        } catch (final IOException | InterruptedException e) {
            // handle the error
        }
    };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM