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!
I recreated your code and added some extra debugging output by creating a class to print the output from process:
In the main method I then started an instance of this before calling
waitFor():The output from this is:
Because the command isn’t executed in a shell, you first need to call the Windows shell, and pass in the command as an argument:
After changing this the output is now
Return code: 0.I’ve found a strange issue however, in that if you don’t handle the output from the process’s stdout channel, for some reason the process does not terminate. To get around this, I’ve had to put in a loop to read and discard the output from the process: