且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Java运行shell脚本并让它在JVM关闭后继续运行?

更新时间:2023-12-05 19:25:28

运行流程时从java开始,您将创建一个shell实例,然后运行该进程。即使在后台运行,该shell也会在此过程完成后退出&

When you run a process from java you are creating a shell instance which then runs the process. The shell will only exit once this process has finished even if it is being run in the background &

To在无头模式下运行一个进程,你需要使用 nohup 命令。有关详细信息,请查看此处

To run a process in headless mode you need to use the nohup command. For details, see here.

用法可能如下所示:

ProcessBuilder processBuilder = new ProcessBuilder("nohup", "sh", "restart.sh");
try {
    processBuilder.directory(new File(System.getProperty("user.dir")));
    processBuilder.redirectErrorStream(false);
    processBuilder.start();
} catch (IOException e) {
    e.printStackTrace();
}