Reputation: 1633
I have a requirement to check if the given windows service say "XYZService" is running fine.
I understand that we can issue a "sc query " command and check the status of it, windows command prompt.
but I don't know how to do in java.
I am using JDK1.6 in my application.
appreciate any help.
Upvotes: 0
Views: 3495
Reputation: 21
With the help of ProcessBuilder we can launch the command prompt(in background) and fetch the status of service.
Process process = new ProcessBuilder("C:\\Windows\\System32\\sc.exe", "query",
serviceName).start(); //serviceName is the name of the service.
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String resultLine;
String consoleOutput = "";
while ((resultLine = br.readresultLine()) != null) {
consoleOutput += resultLine + "\n";
}
if (consoleOutput.contains("STATE")) {
if (consoleOutput.contains("RUNNING")) {
// Service is Running...!!
} else {
// Service is Not Running...!!
}
} else {
// Service Not Found..!!
}
Upvotes: 0
Reputation: 1633
below is the correct code for verifying service!
Process process = Runtime.getRuntime().exec("sc query "+nameOfService);
Scanner reader = new Scanner(process.getInputStream(), "UTF-8");
while(reader.hasNextLine())
if(reader.nextLine().contains(serviceNAME))
return true;
return false;
Upvotes: 2
Reputation: 11939
This works for me:
public boolean isProcessRunning(final String processName) throws Exception{
final Process process = Runtime.getRuntime().exec("tasklist");
final Scanner reader = new Scanner(process.getInputStream(), "UTF-8");
while(reader.hasNextLine())
if(reader.nextLine().startsWith(processName))
return true;
return false;
}
Note: With the method above, you have to enter the exact process name (case sensitive). Here is what the table looks like:
Upvotes: 1