java 如何成功杀死一个java进程并在unix中重新启动它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6131170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:28:16  来源:igfitidea点击:

How to successfully kill a java process and restart it in unix?

javaunixprocesscentoskill

提问by Kyle

I've been trying to run my java program overnight but I need to restart it sometimes to save it's progress and completely reboot the machine. After a few hours I have the program save its progress and execute a little restart file to restart the program.

我一直试图在一夜之间运行我的 java 程序,但有时我需要重新启动它以保存它的进度并完全重新启动机器。几个小时后,我让程序保存它的进度并执行一个小的重启文件来重新启动程序。

void restartServer() {
    try {
        Runtime rt = Runtime.getRuntime();
        rt.exec("./restart.bat");
    } catch (java.io.IOException err) {
        logError(err.getMessage());
    }
}

Inside restart.bat I have:

在 restart.bat 里面我有:

echo Restarting Server
killall -9 java
sleep 2;
nohup java -Xmx200m -classpath bin server.Main;

However it doesn't work. It says:

但是它不起作用。它说:

[root@linode java]# ./restart.bat
Restarting Server
: no process killed
: command not found 3:
nohup: appending output to `nohup.out'
: command not found 4:
[root@linode java]#

Why does it say no process killed when there is a java process running? And why does it say command not found? It never restarts the program either.

为什么在有java进程运行时说没有进程被杀死?为什么它说找不到命令?它也永远不会重新启动程序。

采纳答案by Alexander Pogrebnyak

How about putting #!/bin/shor something like it as the first line of your restart.bat

#!/bin/sh或类似的东西作为你的第一行怎么样restart.bat

BTW, .batis a very poor choice of extension on linux system.

顺便说一句,.bat在 linux 系统上是一个非常糟糕的扩展选择。

回答by jontro

Instead of starting the app from the server itself, you could do a script like this:

您可以执行如下脚本,而不是从服务器本身启动应用程序:

#!/bin/sh
while [ 1 ]
do
    nohup java -Xmx200m -classpath bin server.Main;
done

This will restart the process once it quits. And after your savestate just exit and it will restart automatically.

一旦退出,这将重新启动该过程。在您的保存状态退出后,它会自动重新启动。

回答by clarson

is it safe for your JVM to be killed like that mid process? If not, you might consider a JMX bean to check the program status and do the shutdown from inside the JVM.

您的 JVM 像中间过程那样被杀死是否安全?如果没有,您可能会考虑使用 JMX bean 来检查程序状态并从 JVM 内部执行关闭操作。