Need a way to check status of Windows service programmatically

前端 未结 9 899
走了就别回头了
走了就别回头了 2021-01-04 10:11

Here is the situation:

I have been called upon to work with InstallAnywhere 8, a Java-based installer IDE, of sorts, that allows starting and stopping of windows ser

9条回答
  •  星月不相逢
    2021-01-04 10:44

    Based on the other answers I constructed the following code to check for Windows Service status:

    public void checkService() {
      String serviceName = "myService";  
    
      try {
        Process process = new ProcessBuilder("C:\\Windows\\System32\\sc.exe", "query" , serviceName ).start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
    
        String line;
        String scOutput = "";
    
        // Append the buffer lines into one string
        while ((line = br.readLine()) != null) {
            scOutput +=  line + "\n" ;
        }
    
        if (scOutput.contains("STATE")) {
            if (scOutput.contains("RUNNING")) {
                System.out.println("Service running");
            } else {
                System.out.println("Service stopped");
            }       
        } else {
            System.out.println("Unknown service");
        }
      } catch (IOException e) {
        e.printStackTrace();
      } 
    }
    

提交回复
热议问题