1

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
Community
  • 1
  • 1
Binyamin Regev
  • 914
  • 5
  • 19
  • 31

1 Answers1

0

You can use Windows Service Controller (sc) command from cmd.exe, like this:

String[] script = {"cmd.exe", "/c", "sc", "start", "Tomcat8"}; 
Runtime.getRuntime().exec(script);

That is provided you have Tomcat service installed and named Tomcat8. You can check for installation instructions here.

Shem
  • 565
  • 2
  • 10
  • Very Cool! it works. – Binyamin Regev Dec 13 '16 at 08:52
  • And how can I query whether the Windows service is running (started)? I saw an existing answer, but it didn't work, see my edited question. – Binyamin Regev Dec 13 '16 at 14:31
  • @BinyaminRegev you can't use `process.isAlive`, because it only checks if the process you spawned is alive (that is the `cmd.exe`, although I don't know why the answer varies for your different calls. Check out this thread for info how to check the status of a service: https://stackoverflow.com/questions/5388888/find-status-of-windows-service-from-java-application – Shem Dec 13 '16 at 15:11