简体   繁体   English

Java ProcessBuilder 守护进程在退出 jvm 后将 output 重定向到文件而不终止进程

[英]Java ProcessBuilder daemon process redirect output to file without terminating process after exiting jvm

I want to recreate java -jar [jar] &>logfile & in java via the ProcessBuilder.我想通过 ProcessBuilder 在 java 中重新创建java -jar [jar] &>logfile &

Here's my current code:这是我当前的代码:

File outFile = new File(".."); // logfile
ProcessBuilder builder = new ProcessBuilder(args);  // args = ["java", "-jar", "[jar]"]
builder.redirectError(outFile);
builder.redirectOutput(outFile);
Process process = builder.start();

The said jar is a web server and is supposed to run forever.上述 jar 是 web 服务器,应该永远运行。 But when I exit the java process that spawned the server it is also terminated.但是,当我退出生成服务器的 java 进程时,它也会终止。

My question now is: How do I tell the ProcessBuilder to execute the command in a background thread that doesn't terminate when the caller exits?我现在的问题是:如何告诉 ProcessBuilder 在调用者退出时不会终止的后台线程中执行命令?

Prepending the args with nohup has not changed this behavior, using:使用nohup前置参数并没有改变这种行为,使用:

args = ["nohup", "java", "-jar", "[jar]"]

I've also tried我也试过

args = ["nohup", "java", "-jar", "[jar]", "&"]

Both of these do not work, neither on windows or linux这两个都不起作用,在 windows 或 linux 上都不起作用

According to https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html#tag_16_111_03 if parent processes ignore signals, their children will too.根据https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html#tag_16_111_03如果父进程忽略信号,他们的孩子也会忽略信号。

So the easy fix here is to start my parent java process with nohup or append a &所以这里的简单解决方法是使用nohup或 append a &启动我的父 java 进程

before start this process, redirect input,output and erorr string to other file, then start the process, this process will not be closed after main process exit.在启动该进程之前,将输入、output 和 erorr 字符串重定向到其他文件,然后启动该进程,主进程退出后该进程不会关闭。

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

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