简体   繁体   中英

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). 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()). 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. 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

You could leverage a Windows Service for that. 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):

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?

Good luck!

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

Multi platform, 6 lines. The only catch is that the port 1044 (You can change it) must be open. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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