0

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?

splinter123
  • 1,183
  • 1
  • 14
  • 34
  • 3
    I believe that this command also catches the current instance, so it terminates all other instances, and this one as well. – parakmiakos Nov 21 '14 at 13:52
  • Isn't it a bad way to terminate the currently running process instead of not starting the new process at all? Just a little thought... – bobbel Nov 21 '14 at 13:54
  • yes it must catch the current instance, I don't know why I hadn't thought of it. But the problem remains: how to execute a program only if there are not other instances already running? – splinter123 Nov 21 '14 at 13:56
  • Just check if there are another processes like yours and terminate your own instance with something like `System.exit(0)`. – bobbel Nov 21 '14 at 13:58

3 Answers3

1

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

Community
  • 1
  • 1
Tim Jansen
  • 3,330
  • 2
  • 23
  • 28
1
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.

nathanfranke
  • 775
  • 1
  • 9
  • 19
0

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!

Community
  • 1
  • 1
jlr
  • 1,362
  • 10
  • 17