I know how to start/stop Tomcat from a Java program using BAT files (and .sh files in linux/unix). it's done like this:
String command = "c:\program files\tomcat\bin\startup.bat";//for linux use .sh
Process child = Runtime.getRuntime().exec(command);
Note: Use CATALINA_HOME to make this code more dynamic.
Now I am looking for a way to start/stop Tomcat's Windows service from a Java program. I mean, I want to start/stop Tomcat from Java as if I entered Control Panel --> Administrative Tools --> Services. Can it be done this way, or using BAT files is the maximum we can do?
I saw the question start windows service from java, but when I tried it with "sc" then process.isAlive()
was ALWAYS false
and when I used "net" instead of "sc" then process.isAlive()
is always true
, even when I used serviceName = "aliceinwonderland"
. Sample of the code I used:
//String servicename = "Dhcp"; // real service that exists and started.
String serviceName = "aliceinwonderland"; // fiction, no such service
//String[] script = {"cmd.exe", "/c", "sc", "query", serviceName, "|", "find", "/C", "\"RUNNING\""};
String[] script = {"cmd.exe", "/c", "net", "query", serviceName, "|", "find", "/C", "\"RUNNING\""};
Process process = Runtime.getRuntime().exec(command);
boolean alive = process.isAlive(); // using "sc" = false; using "net" = true