本文介绍了需要一种以编程方式检查Windows服务状态的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是这种情况:

我被要求使用InstallAnywhere 8,这是一种基于Java的安装程序IDE,允许启动和停止Windows服务,但没有内置方法来查询其状态。幸运的是,它允许您在Java中创建自定义操作,可以在安装过程中随时调用(通过我认为是一个相当复杂的API)。

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.

IDE也是允许调用批处理脚本,所以这也是一个选项,虽然一旦脚本运行,几乎没有办法验证它是否成功,所以我试图避免这种情况。

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.

欢迎任何建议或批评。

推荐答案

这就是我必须做的事情。这很难看,但效果很好。

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 是一个私有方法,它将给定的字符串作为命令行进程运行并返回结果输出。正如我所说,丑陋,但有效。希望这会有所帮助。

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.

这篇关于需要一种以编程方式检查Windows服务状态的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 00:09