3

I want to start and stop a jar file using another jar file or java class. I am able to start the jar file using this command:

Runtime run=Runtime.getRuntime();
Process process=run.exec("java -jar setvalue.jar");

The process is started and working fine. But I am not getting how I can close that process from other java class / jar file. I want to run setvalue.jar file as a background process.And able to start and stop that using other java file and jar file.

Can some one have an idea how can I do that?

3 Answers 3

2

One option will be in your setvalue.jar Program create a thread running in while(true) loop which keeps looking to a file in certain place and whenever this thread find that file it will call System.exit to kill current JVM. When you want to exit that program just create that file with another java program of use "touch" to create in linux.

2

You can stop the process from the class which created it:

Runtime run=Runtime.getRuntime();
Process process=run.exec("java -jar setvalue.jar");

// Do stuff

process.destroy();

I don't think it is easy (or recommended) to attempt to stop an independent process using Java. However, if you are using a UNIX based system you can use the Runtime object to exec the ps command to find your process and then kill it.

1
  • I know this works for Windows, but does it also work for Linux and Ma? Jun 1, 2014 at 18:35
2

If you're just looking to start your second jar file in the background you can use:

Process process=run.exec("nohup java -jar setvalue.jar &")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.