I want to stop a Java program that has been started using the command prompt in Windows.
How is it possible to shut it down using some other running Java program?
I want to stop a Java program that has been started using the command prompt in Windows.
How is it possible to shut it down using some other running Java program?
If you want to program to terminate or stop, just type in
System.exit(0);
Although System.exit(1);
will indicate that a "non-zero" exit code occurred which usually means something wrong happened. User 0 if it exits and everything is fine. Use non-zero (like 1) to indicate that there was an error (like a non-existent file or something).
If you want to stop the java program from another java program, you first have to get the process id of the java program. Once this process ID is known, you can kill it with a system call (just like you would in a terminal).
For example, if I had this Java program running indefinitly:
import java.lang.management.ManagementFactory;
public class Test {
public static void main(String[] args) {
System.out.println("Hello, World");
System.out.println(ManagementFactory.getRuntimeMXBean().getName());
while (true) {
int i = 0;
}
}
}
I could see it's process ID (for example 123
) and kill it with the following command.
$ kill 123
Once this is done, you have to find some way for it to output this data to another java program after it asks for it. Then once the process ID is known, you would administer a system call or shell exec.
import java.lang.* ;
public class Shell
{
public static void main(String[] args)
{
try {
String cmd = "kill 123";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd) ;
} catch (Exception ex) {
System.out.println("SOMETHING WENT WRONG");
}
}
}
Node that all shell commands or run.exec
must catch the exception since it is thrown. It must be in a try catch block or it won't compile.
Hope this helps.