Need a way to check status of Windows service programmatically

前端 未结 9 1040
走了就别回头了
走了就别回头了 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:49

    here's what I had to do. It's ugly, but it works beautifully.

    String STATE_PREFIX = "STATE              : ";
    
    String s = runProcess("sc query \""+serviceName+"\"");
    // check that the temp string contains the status prefix
    int ix = s.indexOf(STATE_PREFIX);
    if (ix >= 0) {
      // compare status number to one of the states
      String stateStr = s.substring(ix+STATE_PREFIX.length(), ix+STATE_PREFIX.length() + 1);
      int state = Integer.parseInt(stateStr);
      switch(state) {
        case (1): // service stopped
          break;
        case (4): // service started
          break;
       }
    }
    

    runProcess is a private method that runs the given string as a command line process and returns the resulting output. As I said, ugly, but works. Hope this helps.

提交回复
热议问题