如何在 Java 中完全独立地运行进程 [英] How to run a proccess completely seperate in Java

查看:106
本文介绍了如何在 Java 中完全独立地运行进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Java 程序,它使用 ProcessBuilder 启动另一个进程,如下所示:

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

在进程开始执行(一个不应终止的小 Ruby 脚本)一段时间后,Java 程序退出.

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

问题是,一旦 Java 程序执行完毕,所有子进程都将关闭,Ruby 脚本也是如此.

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

我发现了一些类似的问题,但答案始终是,流程是独立的.但在我的情况下不是这样,如果 Java 程序退出,Ruby 代码将始终停止执行.

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.

我在带有 Java 8u66 的 Debian Jessie 系统上尝试了 Java 代码

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

推荐答案

问题是,一旦 Java 程序执行完毕,所有子进程都将关闭,Ruby 脚本也是如此.

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

在 *nix 系统(POSIX 真的,包括 Debian Linux)上,进程被发送一个 HUP 信号(SIGHUP挂断)当其父进程结束时.启动时可以使用nohup(1)命令忽略进程的挂断的子进程.

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.

或者,您可以潜在地使用 Ruby Signal 模块 并使用 Signal.trap(HUP) 以其他方式处理它.

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

这篇关于如何在 Java 中完全独立地运行进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆