何となく Blog by Jitta
Microsoft .NET 考

目次

Blog 利用状況
  • 投稿数 - 761
  • 記事 - 18
  • コメント - 37042
  • トラックバック - 222
ニュース
  • IE7以前では、表示がおかしい。div の解釈に問題があるようだ。
    IE8の場合は、「互換」表示を OFF にしてください。
  • 検索エンジンで来られた方へ:
    お望みの情報は見つかりましたか? よろしければ、コメント欄にどのような情報を探していたのか、ご記入ください。
It's ME!
  • はなおか じった
  • 世界遺産の近くに住んでます。
  • Microsoft MVP for Visual Developer ASP/ASP.NET 10, 2004 - 9, 2011
広告

記事カテゴリ

書庫

日記カテゴリ

ギャラリ

その他

わんくま同盟

同郷

 

サービスを再起動させてみます。唐突ですが、そういう必要が生じたので。

Visual Studio 2008 にて、C++ の Win32 コンソール アプリケーションです。PSDK API を使うので、C++。

説明するのが面倒なので、さくっと行きます。

サービスを制御するには、まず、サービス マネージャにアクセスします。このとき、いくつかの特権が必要です。今回は、考えないことにします。

「再起動」すなわち、「停止してから起動」というコマンドは、無いようです。そこで、「停止する」というコマンドと、「起動する」というコマンドを発行します。

コマンドを発行するには、OpenService 関数で、サービスのハンドラを捕まえ、ControlService 関数を使用します。起動は、StartService 関数です。

サービスは、Windows Service を作成したことがある方ならおわかりだと思いますが、起動指示から30秒以内に起動状態にならなければなりません。逆に言うと、起動を指示したからといってすぐに起動するわけではありません。停止も同じ。よって、停止を指示してから、完全に停止するまで待つ必要があります。また、起動も同じく、完全に起動するまで待ちます。待っている間、QueryServiceStatus 関数で現在のステータスを取ります。

  1. サービス マネージャにアクセスする。

  2. 指定のサービスにアクセスする。

  3. 停止信号を送る。

  4. 停止するまで待つ。

    1. 状態を見る。

    2. SERVICE_STOPPED でなければ1秒待つ。
      SERVICE_STOPPED なら戻る。

    3. 累積で30秒待っていれば、タイムアウトとする。
      そうでなければ繰り返す。

  5. 起動する。

  6. 起動するまで待つ。

    1. 状態を見る。

    2. SERVICE_RUNNING でなければ1秒待つ。
      SERVICE_RUNNING なら戻る。

    3. 累積で30秒待っていれば、タイムアウトとする。
      そうでなければ繰り返す。

そんなこんなで、次のようなコード。タイトルにカッコがついているのは、これで終われないから。

このコードでは、破棄しなければならないリソースを確保したら、次の関数を呼び出す様にしました。これにより、リソースを使うところ=次の関数内では、何らかのエラーが発生したら遠慮なしに return することができます。なぜこんな作りにしてあるかというと、本当は .c なコードで使っているから(涙)

で、こいつを元に、「C++(あるいはオブジェクト指向言語)って、C に比べてこんな利点があるんだよ。」ってことが説明できるかな、と。。。セッション資料作った方が面白いような気もしてきた。


// RestartService.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
//

#include "stdafx.h"
#include 

DWORD RestartService(LPCTSTR serviceName);
DWORD StopThenStartService(SC_HANDLE manager, LPCTSTR serviceName);
DWORD StopServiceWithWaiting(SC_HANDLE service);
DWORD StartServiceWithWaiting(SC_HANDLE service);
DWORD WaitServiceUntilStatus(SC_HANDLE service, DWORD state, int timeout = 30);

int _tmain(int argc, _TCHAR* argv[])
{
    _tsetlocale(LC_ALL, _T("japanese_japan"));
    if (argc < 2) {
        _putts(_T("引数で、サービス名を指定してください。\n"));
        return ERROR_BAD_ARGUMENTS;
    } else {
        _tprintf(_T("サービス \"%s\" の起動・停止結果 : %d\n")
            , argv[1]
            ,RestartService(argv[1]));
    }
    return 0;
}

// 指定されたサービスを再起動する。
// serviceName : サービス名
DWORD RestartService(LPCTSTR serviceName)
{
    if (serviceName == NULL) { return ERROR_BAD_ARGUMENTS; }

    SC_HANDLE manager;
    manager = OpenSCManager(NULL    /* ローカル コンピュータ */
        , NULL                        /* 規定のマネージャ */
        , SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE | GENERIC_EXECUTE
        );

    if (manager != NULL) {
        DWORD result;
        result = StopThenStartService(manager, serviceName);
        (void) CloseServiceHandle(manager);
        return result;

    } else {
        return GetLastError();
    }
}

// 指定されたサービスを停止させ、起動する。
// manager : サービス マネージャ
// serviceName : サービス名
DWORD StopThenStartService(SC_HANDLE manager, LPCTSTR serviceName)
{
    if (manager == NULL || serviceName == NULL) { return ERROR_BAD_ARGUMENTS; }

    SC_HANDLE    service;
    service = OpenService(manager, serviceName, GENERIC_EXECUTE | GENERIC_READ);

    if (service != NULL) {
        DWORD result;
        // サービスを停止する
        if ((result = StopServiceWithWaiting(service)) == ERROR_SUCCESS) {
            // サービスを起動する
            result = StartServiceWithWaiting(service);
        }
        (void) CloseServiceHandle(service);
        return result;

    } else {
        return GetLastError();
    }
}

// 指定のサービスを停止させ、停止するまで待つ。
// service : サービスのハンドラ
DWORD StopServiceWithWaiting(SC_HANDLE service)
{
    if (service == NULL) { return ERROR_BAD_ARGUMENTS; }

    SERVICE_STATUS status;
    BOOL ret = ControlService(service, SERVICE_CONTROL_STOP, &status);
    DWORD result = GetLastError();
    if (ret == TRUE || result == ERROR_SERVICE_NOT_ACTIVE) {
        result = WaitServiceUntilStatus(service, SERVICE_STOPPED);
    }
    return result;
}

// 指定のサービスを起動させ、起動するまで待つ。
// service : サービスのハンドラ
DWORD StartServiceWithWaiting(SC_HANDLE service)
{
    if (service == NULL) { return ERROR_BAD_ARGUMENTS; }

    BOOL ret = StartService(service, 0, NULL);
    DWORD result = GetLastError();
    if (ret == TRUE || result == ERROR_SERVICE_ALREADY_RUNNING) {
        result = WaitServiceUntilStatus(service, SERVICE_RUNNING);
    }
    return result;
}

// サービスが、指定の状態になるまで待つ。
// service : サービスのハンドラ
// state : 期待する状態
// timeout : 期待する状態になるまで待機する秒数(既定値 30)
DWORD WaitServiceUntilStatus(SC_HANDLE service, DWORD state, int timeout)
{
    DWORD result;
    SERVICE_STATUS status;
    int count = 0;
    while (TRUE) {
        if (QueryServiceStatus(service, &status)) {
            if (status.dwCurrentState == state) {
                result = ERROR_SUCCESS;
                break;
            }
            if (++count > timeout) {
                result = ERROR_SERVICE_REQUEST_TIMEOUT;
                break;
            }
        } else {
            result = GetLastError();
            break;
        }
        Sleep(1000);
    }
    return result;
}
投稿日時 : 2008年8月29日 22:55
コメント
  • # re: サービスを再起動する(フラット)
    渋木宏明(ひどり)
    Posted @ 2008/08/29 23:32
    >そういう必要

    コンソールアプリに仕上げるんなら、net コマンドでよかったのでわ。(サンプルコードだから?)
  • # re: サービスを再起動する(フラット)
    ちゃっぴ
    Posted @ 2008/08/30 0:04
    Windows Sewrvice 再起動するのに特権は必要ないですね。
    Service の ACL で許可されていればどの user からでも扱うこと出来るでしょう。
  • # re: サービスを再起動する(フラット)
    ちゃっぴ
    Posted @ 2008/08/30 0:06
    Windows Sewrvice 再起動するのに特権は必要ないですね。
    Service の ACL で許可されていればどの user からでも扱うこと出来るでしょう。

    > コンソールアプリに仕上げるんなら、net コマンドでよかったのでわ。

    やっぱり API 利用した方が良いのでそういう意味では WMI がお手軽だと思われます。
  • # re: サービスを再起動する(フラット)
    Jitta
    Posted @ 2008/08/30 8:49
    コメントありがとうございます。

    WMI って、Windows 2000 でも使えましたっけ?
    色々事情があって、もとのコードは VC6 だったりします。

    次のネタなのですが、net コマンドって、依存関係をたどってくれるのですか?!だったら、今からでも書き直しますっ!!
  • # re: サービスを再起動する(フラット)
    Jitta
    Posted @ 2008/08/30 8:52
    あ、ここに出したコードがコンソール アプリケーションなのは、説明用に実行できるように、ですよ。実際は、他のところで作っているアプリケーションから呼ばれるライブラリです。
  • # re: サービスを再起動する(フラット)
    ちゃっぴ
    Posted @ 2008/08/30 15:38
    > WMI って、Windows 2000 でも使えましたっけ?

    標準で使えます。
  • # re: サービスを再起動する(フラット)
    渋木宏明(ひどり)
    Posted @ 2008/08/30 18:01
    >やっぱり API 利用した方が良いのでそういう意味では WMI がお手軽だと思われます。

    net コマンドを Process.Start() せいと言っているわけではなく、コンソールコマンドを自作する必要があるの?てことです。

    >net コマンドって、依存関係をたどってくれるのですか?!

    見て、依存サービスがある場合は「いいの?」って訪ねてきたような気がします。
  • # re: サービスを再起動する(フラット)
    ちゃっぴ
    Posted @ 2008/08/30 20:31
    >net コマンドって、依存関係をたどってくれるのですか?!

    勝手に起動しますよ。WMI でも同じだったはずですけど。

    たとえば w3svc を起動するときは IISAdmin は勝手に起動します。
  • # re: サービスを再起動する(フラット)
    Jitta
    Posted @ 2008/08/31 7:09
    InstallShield のカスタム スクリプトなので、net コマンドは無理として、WMI は、抜け落ちてたねぇ(-_-;
  • # サービスを再起動する(問題発生編)
    何となく Blog by Jitta
    Posted @ 2008/09/03 21:50
    サービスを再起動する(問題発生編)
  • # サービスを再起動する(オブジェクト指向的修正編)
    何となく Blog by Jitta
    Posted @ 2008/09/30 22:04
    サービスを再起動する(オブジェクト指向的修正編)
  • # User links about "openservice" on iLinkShare
    Pingback/TrackBack
    Posted @ 2009/01/26 6:48
    User links about "openservice" on iLinkShare
  • # サービスを再起動する(オブジェクト指向的修正編)
    何となく Blog by Jitta
    Posted @ 2010/06/13 23:41
    サービスを再起動する(オブジェクト指向的修正編)
  • # サービスを再起動する(問題発生編)
    何となく Blog by Jitta
    Posted @ 2010/06/13 23:42
    サービスを再起動する(問題発生編)
  • # Thanks for the insig
    car rental Bordeaux airport singapore
    Posted @ 2015/05/15 5:58
    Thanks for the insight. It brings light into the dark!
  • # mJXXGzDUxFsIAompW
    https://amzn.to/365xyVY
    Posted @ 2021/07/03 3:32
    Magnificent site. Lots of useful info here.
  • # best erectile pills
    hydroxychloroquine sulfate 200mg
    Posted @ 2021/07/09 1:44
    chloroquine phosphate vs hydroxychloroquine https://plaquenilx.com/# where to get hydroxychloroquine
  • # re: ??????????(????)
    hydrocychloroquine
    Posted @ 2021/07/26 12:22
    sulfur effects on body https://chloroquineorigin.com/# what is hcq drug
  • # qbewvebsehqo
    dwedayigjt
    Posted @ 2021/11/27 16:35
    where can i buy hydroxychloroquine https://aralenphosphates.com/
  • # zohcvpenholc
    dwedayuvhf
    Posted @ 2021/12/02 0:48
    hydroxychloroquine malaria https://hydro-chloroquine.com/
  • # zweuqqrypvem
    dwedaynwyd
    Posted @ 2021/12/03 1:32
    https://hydrochloroquineada.com/ chloroquine phosphate tablets
  • # buy ivermectin for humans uk http://stromectolabc.com/
    ivermectin 6mg dosage
    Busjdhj
    Posted @ 2022/02/08 2:37
    buy ivermectin for humans uk http://stromectolabc.com/
    ivermectin 6mg dosage
  • # doxycycline 100 mg https://doxycyline1st.com/
    doxycycline monohydrate
    Doxycycline
    Posted @ 2022/02/26 19:51
    doxycycline 100 mg https://doxycyline1st.com/
    doxycycline monohydrate
  • # szziecbtjtxa
    ijjusrrz
    Posted @ 2022/05/26 5:37
    fougera erythromycin ophthalmic ointment https://erythromycinn.com/#
  • # paxlovid ingredients list https://paxlovid.best/
    molnupiravir brand name
    Paxlovid
    Posted @ 2022/09/08 7:25
    paxlovid ingredients list https://paxlovid.best/
    molnupiravir brand name
  • # what is the best ed pill https://erectiledysfunctionpills.shop/
    Erectile
    Posted @ 2022/10/14 22:41
    what is the best ed pill https://erectiledysfunctionpills.shop/
  • # prednisone 40 mg price https://prednisone20mg.icu/
    Prednisone
    Posted @ 2022/10/15 13:13
    prednisone 40 mg price https://prednisone20mg.icu/
  • # generic prednisone online https://prednisone20mg.site/
    prednisone 50
    Prednisone
    Posted @ 2022/11/15 17:50
    generic prednisone online https://prednisone20mg.site/
    prednisone 50
  • # buy prednisone 40 mg https://prednisonepills.site/
    prednisone without prescription.net
    Prednisone
    Posted @ 2022/11/28 23:44
    buy prednisone 40 mg https://prednisonepills.site/
    prednisone without prescription.net
  • # dating best sites https://datingsiteonline.site/
    good dating site
    Tading
    Posted @ 2022/12/05 23:41
    dating best sites https://datingsiteonline.site/
    good dating site
  • # free date sites https://datingonlinehot.com/
    free for online chatting with singles
    Dating
    Posted @ 2022/12/09 19:12
    free date sites https://datingonlinehot.com/
    free for online chatting with singles
  • # chloroquine canada
    MorrisReaks
    Posted @ 2022/12/25 14:10
    chloroquine without a doctor prescription https://hydroxychloroquinex.com/
  • # hydroxychloroquine pills for sale
    MorrisReaks
    Posted @ 2022/12/29 11:50
    http://www.hydroxychloroquinex.com/# aralen online canada
  • # medication for ed dysfunction https://edpills.science/
    top rated ed pills
    EdPills
    Posted @ 2023/01/07 13:43
    medication for ed dysfunction https://edpills.science/
    top rated ed pills
  • # best internet dating sites https://datingonline1st.com/
    dating sinulator online
    Dating
    Posted @ 2023/01/17 22:25
    best internet dating sites https://datingonline1st.com/
    dating sinulator online
  • # Cautions. Prescription Drug Information, Interactions & Side.
    https://edonlinefast.com
    Get here. drug information and news for professionals and consumers.
    EdOnline
    Posted @ 2023/02/17 7:14
    Cautions. Prescription Drug Information, Interactions & Side.
    https://edonlinefast.com
    Get here. drug information and news for professionals and consumers.
  • # Misoprostol 200 mg buy online - https://cytotecsale.pro/#
    Cytotec
    Posted @ 2023/04/28 23:24
    Misoprostol 200 mg buy online - https://cytotecsale.pro/#
  • # online medications https://pillswithoutprescription.pro/#
    PillsPresc
    Posted @ 2023/05/14 22:07
    online medications https://pillswithoutprescription.pro/#
  • # Paxlovid buy online https://paxlovid.bid/ paxlovid cost without insurance
    Paxlovid
    Posted @ 2023/10/25 18:22
    Paxlovid buy online https://paxlovid.bid/ paxlovid cost without insurance
  • # doxycycline medication https://doxycycline.forum/ doxycycline tetracycline
    Doxycycline
    Posted @ 2023/11/25 9:03
    doxycycline medication https://doxycycline.forum/ doxycycline tetracycline
  • # ed pills online https://edpills.tech/# ed treatments
    EdPills
    Posted @ 2023/12/23 4:37
    ed pills online https://edpills.tech/# ed treatments
  • # paxlovid generic https://paxlovid.guru/ paxlovid
    Paxlovid
    Posted @ 2024/01/11 13:37
    paxlovid generic https://paxlovid.guru/ paxlovid
  • # eva elfie hot https://evaelfie.site/ eva elfie new videos
    EvaElfie
    Posted @ 2024/03/07 2:07
    eva elfie hot https://evaelfie.site/ eva elfie new videos
  • # aviator mo&#231;ambique https://aviatormocambique.site aviator bet
    AviatorMaz
    Posted @ 2024/03/11 20:49
    aviator mo&#231;ambique https://aviatormocambique.site aviator bet
  • # Abortion pills online https://cytotec.club/ buy cytotec online fast delivery
    Cytotec
    Posted @ 2024/04/27 18:57
    Abortion pills online https://cytotec.club/ buy cytotec online fast delivery
タイトル
名前
Url
コメント