Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a way to check status of Windows service programmatically

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 services, but has no built-in method to query their states. Fortunately, it allows you to create custom actions in Java which can be called at any time during the installation process (by way of what I consider to be a rather convoluted API).

I just need something that will tell me if a specific service is started or stopped.

The IDE also allows calling batch scripts, so this is an option as well, although once the script is run, there is almost no way to verify that it succeeded, so I'm trying to avoid that.

Any suggestions or criticisms are welcome.

like image 412
Troy Avatar asked Dec 02 '08 16:12

Troy


1 Answers

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.

like image 132
Yuval Avatar answered Oct 12 '22 16:10

Yuval