13

状況は次のとおりです。

私は、Windows サービスの開始と停止を可能にする Java ベースのインストーラー IDE である InstallAnywhere 8 を使用するように求められましたが、それらの状態を照会する組み込みメソッドはありません。幸いなことに、Java でカスタム アクションを作成することができます。これは、インストール プロセス中にいつでも呼び出すことができます (かなり複雑な API と思われる方法を使用します)。

特定のサービスが開始または停止されているかどうかを教えてくれるものが必要です。

IDE ではバッチ スクリプトを呼び出すこともできるため、これもオプションですが、スクリプトを実行すると、成功したかどうかを確認する方法がほとんどないため、それを回避しようとしています。

提案や批判は大歓迎です。

4

10 に答える 10

18

これが私がしなければならなかったことです。醜いですが、美しく機能します。

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指定された文字列をコマンド ライン プロセスとして実行し、結果の出力を返すプライベート メソッドです。私が言ったように、醜いですが、うまくいきます。お役に立てれば。

于 2008-12-02T16:42:25.647 に答える
6

小さな VBS をオンザフライで作成し、起動してリターン コードを取得できます。

import java.io.File;
import java.io.FileWriter;

public class VBSUtils {
  private VBSUtils() {  }

  public static boolean isServiceRunning(String serviceName) {
    try {
        File file = File.createTempFile("realhowto",".vbs");
        file.deleteOnExit();
        FileWriter fw = new java.io.FileWriter(file);

        String vbs = "Set sh = CreateObject(\"Shell.Application\") \n"
                   + "If sh.IsServiceRunning(\""+ serviceName +"\") Then \n"
                   + "   wscript.Quit(1) \n"
                   + "End If \n"
                   + "wscript.Quit(0) \n";
        fw.write(vbs);
        fw.close();
        Process p = Runtime.getRuntime().exec("wscript " + file.getPath());
        p.waitFor();
        return (p.exitValue() == 1);
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return false;
  }


  public static void main(String[] args){
    //
    // DEMO
    //
    String result = "";
    msgBox("Check if service 'Themes' is running (should be yes)");
    result = isServiceRunning("Themes") ? "" : " NOT ";
    msgBox("service 'Themes' is " + result + " running ");

    msgBox("Check if service 'foo' is running (should be no)");
    result = isServiceRunning("foo") ? "" : " NOT ";
    msgBox("service 'foo' is " + result + " running ");
  }

  public static void msgBox(String msg) {
    javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
       null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION);
  }
}
于 2008-12-03T12:22:16.980 に答える
5

他の回答に基づいて、Windows サービスのステータスを確認するために次のコードを作成しました。

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();
  } 
}
于 2014-01-22T11:23:50.067 に答える
3

私は何年もインストーラーを扱ってきましたが、秘訣は独自の EXE を作成し、セットアップ時に呼び出すことです。これにより、エラーが発生した場合に正確なエラー メッセージを表示するなどの優れた柔軟性が提供され、成功ベースの戻り値があるため、インストーラーは何が起こったのかを知ることができます。

Windows サービス (C++) の状態を開始、停止、およびクエリする方法は次のとおり です

于 2008-12-02T16:24:48.537 に答える
2

私は過去に Java Service Wrapper で運が良かったことがあります。ご利用の状況によっては、有料でご利用いただく場合がございます。しかし、Java をサポートするクリーンなソリューションを提供し、InstallAnywhere 環境でほとんど問題なく (私が思うに) 使用できます。これにより、Unix ボックスでもサービスをサポートできるようになります。

http://wrapper.tanukisoftware.org/doc/english/download.jsp

于 2008-12-02T17:47:03.127 に答える
1

暗闇でのショットですが、Install Anywhere Java ドキュメントを見てください。

具体的には、

/javadoc/com/installshield/wizard/platform/win32/Win32Service.html

クラス:

com.installshield.wizard.platform.win32
Interface Win32Service

All Superinterfaces:
    Service 

メソッド:

public NTServiceStatus queryNTServiceStatus(String name)
                                     throws ServiceException

    Calls the Win32 QueryServiceStatus to retrieve the status of the specified service. See the Win32 documentation for this API for more information.

    Parameters:
        name - The internal name of the service. 
    Throws:
        ServiceException
于 2008-12-02T19:12:57.260 に答える
1

これは、ストレートな C# / P/Invoke ソリューションです。

        /// <summary>
    /// Returns true if the specified service is running, or false if it is not present or not running.
    /// </summary>
    /// <param name="serviceName">Name of the service to check.</param>
    /// <returns>Returns true if the specified service is running, or false if it is not present or not running.</returns>
    static bool IsServiceRunning(string serviceName)
    {
        bool rVal = false;
        try
        {
            IntPtr smHandle = NativeMethods.OpenSCManager(null, null, NativeMethods.ServiceAccess.ENUMERATE_SERVICE);
            if (smHandle != IntPtr.Zero)
            {
                IntPtr svHandle = NativeMethods.OpenService(smHandle, serviceName, NativeMethods.ServiceAccess.ENUMERATE_SERVICE);
                if (svHandle != IntPtr.Zero)
                {
                    NativeMethods.SERVICE_STATUS servStat = new NativeMethods.SERVICE_STATUS();
                    if (NativeMethods.QueryServiceStatus(svHandle, servStat))
                    {
                        rVal = servStat.dwCurrentState == NativeMethods.ServiceState.Running;
                    }
                    NativeMethods.CloseServiceHandle(svHandle);
                }
                NativeMethods.CloseServiceHandle(smHandle);
            }
        }
        catch (System.Exception )
        {

        }
        return rVal;
    }

public static class NativeMethods
{
    [DllImport("AdvApi32")]
    public static extern IntPtr OpenSCManager(string machineName, string databaseName, ServiceAccess access);
    [DllImport("AdvApi32")]
    public static extern IntPtr OpenService(IntPtr serviceManagerHandle, string serviceName, ServiceAccess access);
    [DllImport("AdvApi32")]
    public static extern bool CloseServiceHandle(IntPtr serviceHandle);
    [DllImport("AdvApi32")]
    public static extern bool QueryServiceStatus(IntPtr serviceHandle, [Out] SERVICE_STATUS status);

    [Flags]
    public enum ServiceAccess : uint
    {
        ALL_ACCESS = 0xF003F,
        CREATE_SERVICE = 0x2,
        CONNECT = 0x1,
        ENUMERATE_SERVICE = 0x4,
        LOCK = 0x8,
        MODIFY_BOOT_CONFIG = 0x20,
        QUERY_LOCK_STATUS = 0x10,
        GENERIC_READ = 0x80000000,
        GENERIC_WRITE = 0x40000000,
        GENERIC_EXECUTE = 0x20000000,
        GENERIC_ALL = 0x10000000
    }

    public enum ServiceState
    {
        Stopped = 1,
        StopPending = 3,
        StartPending = 2,
        Running = 4,
        Paused = 7,
        PausePending =6,
        ContinuePending=5
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public class SERVICE_STATUS
    {
        public int dwServiceType;
        public ServiceState dwCurrentState;
        public int dwControlsAccepted;
        public int dwWin32ExitCode;
        public int dwServiceSpecificExitCode;
        public int dwCheckPoint;
        public int dwWaitHint;
    };
}
于 2010-10-21T23:58:01.777 に答える
0

起動時にFile.deleteOnExit()でファイルを作成します。

スクリプト内にファイルが存在することを確認してください。

于 2008-12-02T16:23:04.653 に答える