mahesh
mahesh

Reputation: 1633

how to check particular windows service is running using

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

Answers (3)

Gourav Kaushal
Gourav Kaushal

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

mahesh
mahesh

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

Josh M
Josh M

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:

enter image description here

Upvotes: 1

Related Questions