How to run a proccess completely seperate in Java

好久不见. 提交于 2019-12-13 14:24:59

问题


I have a Java program which starts another process with ProcessBuilder like the following:

String commands[] = {"ruby", "/home/scripts/script.rb"};
ProcessBuilder builder = new ProcessBuilder(commands);
Map<String,String> map = builder.environment();
map.put("TYPE", "sometype");
try {
    builder.start();
} catch (IOException e) {
    e.printStackTrace();
}

Some time after the process starts executing (a small Ruby Script which should not terminate) the Java program exits.

The problem is, once the Java program finishes executing, all sub-processes are closed, also the Ruby Script.

I found some similar questions but the answer was always, the Process is independent. But it is not like that in my case, the Ruby code will always stop executing if the Java program exits.

I tried the Java code on a Debian Jessie System with Java 8u66


回答1:


The problem is, once the Java program finishes executing, all sub-processes are closed, also the Ruby Script.

On *nix systems (POSIX really, including Debian Linux) the process is sent a HUP signal (SIGHUP or hangup) when its' parent process ends. You can use the nohup(1) command when you start a subprocess to ignore the hangup from the child process.

Alternatively, you could potentially make use of the Ruby Signal Module and use Signal.trap(HUP) to handle it some other way.




回答2:


Try to use Process.getOutputStream, wait for output from the process with runs Ruby, and if it takes too much time, then you can run in the background also.



来源:https://stackoverflow.com/questions/34841694/how-to-run-a-proccess-completely-seperate-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!