简体   繁体   English

Java Kill程序(如果已运行)

[英]Java kill program if already running

I would like my java program to check whether another instance of it is already running, and kill it if this is the case (on a Windows platform). 我希望我的java程序检查它的另一个实例是否已经在运行,如果是这种情况,请杀死它(在Windows平台上)。 I'm doing this with the code 我正在用代码做到这一点

String CMD = 
        "wmic PROCESS where \"CommandLine like '%%MyProgram%%'\" Call Terminate";
Process process = Runtime.getRuntime().exec(CMD);

The code executes succesfully and kills the running program if it is found, however once executed it forces also the calling program to exit (there must be some hidden call to System.exit()). 该代码成功执行并杀死正在运行的程序(如果找到了),但是一旦执行,它也会强制调用程序退出(必须对System.exit()进行一些隐藏的调用)。 Is there a way for executing the command without exiting the calling program? 有没有一种方法可以在不退出调用程序的情况下执行命令?

As mentioned in the comments, the command will also kill the new instance. 如注释中所述,该命令还将终止新实例。 There are ways around it, like creating pid files to ensure only one instance is running. 有多种解决方法,例如创建pid文件以确保仅运行一个实例。 But that probably doesn't matter, because there are better ways to do the same. 但这可能并不重要,因为有更好的方法可以做到这一点。

Please check How to implement a single instance Java application and How to allow running only one instance of a java program 请检查如何实现单个实例Java应用程序以及如何仅允许运行Java程序的一个实例。

You could leverage a Windows Service for that. 您可以为此使用Windows服务。 You'll know only one instance will run + you can get it running with no users logged in (if desired). 您将知道只有一个实例可以运行+您可以在没有用户登录的情况下运行它(如果需要)。 Use Apache Commons Daemon with procrun (if only meant for Windows): 将Apache Commons Daemon与procrun一起使用(如果仅适用于Windows):

http://commons.apache.org/proper/commons-daemon/index.html http://commons.apache.org/proper/commons-daemon/procrun.html http://commons.apache.org/proper/commons-daemon/index.html http://commons.apache.org/proper/commons-daemon/procrun.html

A SO reference for more options and exploration daemons and Java: How to Daemonize a Java Program? 有关更多选项和探索守护程序以及Java的SO参考: 如何守护Java程序?

Good luck! 祝好运!

try {
    ServerSocket ss = new ServerSocket(1044);
} catch (IOException e) {
    System.err.println("Application already running!");
    System.exit(-1);
}

Multi platform, 6 lines. 多平台,6条线。 The only catch is that the port 1044 (You can change it) must be open. 唯一的问题是端口1044(可以更改)必须是开放的。 Basically, running the program will establish a "server", but if the port is already a server, it was already started, and it will close. 基本上,运行该程序将建立一个“服务器”,但是如果该端口已经是服务器,则它已经启动,并且将关闭。

Just remember that starting a server on the same port as another server is impossible, which we can use to our advantage. 只需记住,不可能在与另一台服务器相同的端口上启动服务器,这可以为我们带来好处。

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

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