There's plenty of information on running Java apps as services, but I need to know how to detect whether a windows service is running or not. Does anyone know how???
At the DOS prompt, I can run:
tasklist /svc|findstr "NonRunningService"
echo Return code for N onRunningService is %ERRORLEVEL%
tasklist /svc|findstr "RunningService"
echo Return code for RunningService is %ERRORLEVEL%
I get the following:
Return code for NonRunningService is 1
Return code for RunningService is 0
In code, I have:
int retCode = Runtime.getRuntime.exec("tasklist /svc|findstr \"NonRunningService\"").waitFor();
System.out.println("Return code for NonRunningService is " + retCode);
retCode = Runtime.getRuntime.exec("tasklist /svc|findstr \"RunningService\"").waitFor();
System.out.println("Return code for RunningService is " + retCode);
I get the following output
Return code for NonRunningService is 1
Return code for RunningService is 1
According to the JavaDocs, the waitFor() should block until the process finishes, and give me the exit value of the process.
I've also tried using the Process/ProcessBuilder command line calls:
//'tasklist /nh /fi "SERVICES eq RunningService"' will return a line for
// each running service of the requested type.
Process p1 = new ProcessBuilder("tasklist", "/nh", "/fi" "SERVICES eq RunningService").start();
p1.waitFor();
BufferedReader is = new BufferedReader(new InputStreamReader(p1.getInputStream()));
String line = is.readLine();
System.out.println("Service - " + line);
System.out.println("Running? ", (line==null?"No":"Yes");
gives:
Service -
Running? No
even when I get lines in the output at the command line!