IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Windows Discussion :

Comment Redémarrer un service windows sans utiliser la commande System ?


Sujet :

Windows

  1. #1
    Membre du Club Avatar de masterx_goldman
    Inscrit en
    Mai 2008
    Messages
    164
    Détails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 164
    Points : 51
    Points
    51
    Par défaut Comment Redémarrer un service windows sans utiliser la commande System ?
    Bonjour tout le monde,

    Je veux redémarrer un service windows en utilisant un code en C++/API windows.
    J'ai fait un code qui est fonctionel mais qui me sort une console à son exécution ( c'est la console du shell et pas celle de l'application console, car mon application n'a pas de console )
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    system("Net Stop \"ServiceName\"");
    Sleep(5000);
    system("Net Start \"ServiceName\"");
    Dans ce cas, à l'éxécution je reçois deux consoles sucessives et leurs apparitions sont séparées par la durée 5 s ( celle du Sleep )
    Alors, je sais pas s'il ya un moyen dans l'API Windows/C++ ( natif ) pour faire ça sans avoir la console du shell ?

  2. #2
    Membre du Club Avatar de masterx_goldman
    Inscrit en
    Mai 2008
    Messages
    164
    Détails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 164
    Points : 51
    Points
    51
    Par défaut
    Pour info, j'ai trouvé deux fonctions qui parlent de services:
    1)La première apparement est celle que je cherche, elle s'appelle StartService

    BOOL WINAPI StartService(
    __in SC_HANDLE hService,
    __in DWORD dwNumServiceArgs,
    __in_opt LPCTSTR *lpServiceArgVectors
    );
    le lien msdn est le suivant:
    http://msdn.microsoft.com/en-us/libr...8VS.85%29.aspx
    2) La 2ème est apparement une méthode WMI , je sais pas comment l'exploiter car elle prend pas
    de paramètres( je pense que c'est pas aussi simple de l'utiliser puisqu'on parle de MOF dans le lien
    de sa docuementation:

    MOF

    uint32 StopService();
    le lien msdn est le suivant:
    http://msdn.microsoft.com/en-us/libr...8VS.85%29.aspx

    Alors, y'a pas un moyen plus simple que ça ?
    Si les gens de msdn ont codés StartService et pas une fonction StopService du même genre, je serais pas étonné

  3. #3
    Rédacteur

    Avatar de ram-0000
    Homme Profil pro
    Consultant en sécurité
    Inscrit en
    Mai 2007
    Messages
    11 517
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 61
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Consultant en sécurité
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mai 2007
    Messages : 11 517
    Points : 50 367
    Points
    50 367
    Par défaut
    CreateProcess() permet de lancer un programme en masquant console.

    Sinon, une autre possibilité à mon avis moins crade est d'aller demander directement avec l'API de gestion des services
    Raymond
    Vous souhaitez participer à la rubrique Réseaux ? Contactez-moi

    Cafuro Cafuro est un outil SNMP dont le but est d'aider les administrateurs système et réseau à configurer leurs équipements SNMP réseau.
    e-verbe Un logiciel de conjugaison des verbes de la langue française.

    Ma page personnelle sur DVP
    .

  4. #4
    Membre du Club Avatar de masterx_goldman
    Inscrit en
    Mai 2008
    Messages
    164
    Détails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 164
    Points : 51
    Points
    51
    Par défaut
    Citation Envoyé par ram-0000 Voir le message
    CreateProcess() permet de lancer un programme en masquant console.
    Comment je fais ? Je crée un Process dans le main ?
    sur ce lien msdn http://msdn.microsoft.com/en-us/libr...8VS.85%29.aspx il y'a :
    BOOL WINAPI CreateProcess(
    __in_opt LPCTSTR lpApplicationName,
    __inout_opt LPTSTR lpCommandLine,
    __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,
    __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
    __in BOOL bInheritHandles,
    __in DWORD dwCreationFlags,
    __in_opt LPVOID lpEnvironment,
    __in_opt LPCTSTR lpCurrentDirectory,
    __in LPSTARTUPINFO lpStartupInfo,
    __out LPPROCESS_INFORMATION lpProcessInformation
    );
    Alors comment j'exploite ça, j'ai lu un peu la doc, mais à vrai dire je vois pas encore comment exploiter ça ? Est ce que je dois créer un autre exe qui contient le code
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    system("Net Stop \"ServiceName\"");
    Sleep(5000);
    system("Net Start \"ServiceName\"")
    et je lance cet exe par CreateProcess() ou alors c'est autre chose ?

    Sinon, une autre possibilité à mon avis moins crade est d'aller demander directement avec l'API de gestion des services
    J'ai jeté un coups d'oeil rapide sur la lien, mais apparement y'a pas de StopService >_< ou alors y'a une autre procédure un peu plus complexe pour faire ça ( combiner l'appel d'autres fonctions ....)

  5. #5
    Expert éminent sénior
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2005
    Messages
    5 073
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Conseil

    Informations forums :
    Inscription : Février 2005
    Messages : 5 073
    Points : 12 119
    Points
    12 119

  6. #6
    Membre du Club Avatar de masterx_goldman
    Inscrit en
    Mai 2008
    Messages
    164
    Détails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 164
    Points : 51
    Points
    51
    Par défaut
    Bon j'ai trouvé une réponse à ma question :yeah: et voilà un code que j'ai pris de msdn sur lequel j'ai fait quelques modifs de présentation (Rq : sous VS j'ai choisi une application "win32 console application" pour voir le résultat des printf(....) ):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    // ServiceRestarter.cpp*: définit le point d'entrée pour l'application.
    //
    #include "stdafx.h" // à enlever si on n'a pas besoin 
    #include "ServiceRestarter.h"
    #include <windows.h>
    #include <tchar.h>
    #include <strsafe.h>
    #include <aclapi.h>
    #include <stdio.h>
    
    #pragma comment(lib, "advapi32.lib")
    
    TCHAR szSvcName[80]="ServiceName";// Attention ce nom est celui qu'on peut trouver en allant voir dans les propriétés du service, en tappant services.msc( dans le gestionaire des tâches il peut avoir un autre nom sans espace par exemple ... )
    
    SC_HANDLE schSCManager;
    SC_HANDLE schService;
    
    
    VOID __stdcall DoStartSvc(void);
    
    VOID __stdcall DoStopSvc(void);
    
    BOOL __stdcall StopDependentServices(void);
    
    
    int main(int argc, char* argv[])
    {
        
    
        DoStopSvc();
    
        DoStartSvc();
        
            
        
    }
    
    
    
    //
    // Purpose: 
    //   Starts the service if possible.
    //
    // Parameters:
    //   None
    // 
    // Return value:
    //   None
    //
    VOID __stdcall DoStartSvc()
    {
        SERVICE_STATUS_PROCESS ssStatus; 
        DWORD dwOldCheckPoint; 
        DWORD dwStartTickCount;
        DWORD dwWaitTime;
        DWORD dwBytesNeeded;
    
        // Get a handle to the SCM database. 
     
        schSCManager = OpenSCManager( 
            NULL,                    // local computer
            NULL,                    // servicesActive database 
            SC_MANAGER_ALL_ACCESS);  // full access rights 
     
        if (NULL == schSCManager) 
        {
            
            printf("OpenSCManager failed (%d)\n", GetLastError());
            return;
        }
    
        // Get a handle to the service.
    
        schService = OpenService( 
            schSCManager,         // SCM database 
            szSvcName,            // name of service 
            SERVICE_ALL_ACCESS);  // full access 
     
        if (schService == NULL)
        { 
            
    	printf("OpenService failed (%d)\n", GetLastError()); 
            CloseServiceHandle(schSCManager);
            return;
        }    
    
        // Check the status in case the service is not stopped. 
    
        if (!QueryServiceStatusEx( 
                schService,                     // handle to service 
                SC_STATUS_PROCESS_INFO,         // information level
                (LPBYTE) &ssStatus,             // address of structure
                sizeof(SERVICE_STATUS_PROCESS), // size of structure
                &dwBytesNeeded ) )              // size needed if buffer is too small
        {
             
    	printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
            CloseServiceHandle(schService); 
            CloseServiceHandle(schSCManager);
            return; 
        }
    
        // Check if the service is already running. It would be possible 
        // to stop the service here, but for simplicity this example just returns. 
    
        if(ssStatus.dwCurrentState != SERVICE_STOPPED && ssStatus.dwCurrentState != SERVICE_STOP_PENDING)
        {
            printf("Cannot start the service because it is already running\n");
            CloseServiceHandle(schService); 
            CloseServiceHandle(schSCManager);
            return; 
        }
    
        // Save the tick count and initial checkpoint.
    
        dwStartTickCount = GetTickCount();
        dwOldCheckPoint = ssStatus.dwCheckPoint;
    
        // Wait for the service to stop before attempting to start it.
    
        while (ssStatus.dwCurrentState == SERVICE_STOP_PENDING)
        {
            // Do not wait longer than the wait hint. A good interval is 
            // one-tenth of the wait hint but not less than 1 second  
            // and not more than 10 seconds. 
     
            dwWaitTime = ssStatus.dwWaitHint / 10;
    
            if( dwWaitTime < 1000 )
                dwWaitTime = 1000;
            else if ( dwWaitTime > 10000 )
                dwWaitTime = 10000;
    
            Sleep( dwWaitTime );
    
            // Check the status until the service is no longer stop pending. 
     
            if (!QueryServiceStatusEx( 
                    schService,                     // handle to service 
                    SC_STATUS_PROCESS_INFO,         // information level
                    (LPBYTE) &ssStatus,             // address of structure
                    sizeof(SERVICE_STATUS_PROCESS), // size of structure
                    &dwBytesNeeded ) )              // size needed if buffer is too small
            {
                
    	    printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
                CloseServiceHandle(schService); 
                CloseServiceHandle(schSCManager);
                return; 
            }
    
            if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
            {
                // Continue to wait and check.
    
                dwStartTickCount = GetTickCount();
                dwOldCheckPoint = ssStatus.dwCheckPoint;
            }
            else
            {
                if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
                {
                    printf("Timeout waiting for service to stop\n");
                    CloseServiceHandle(schService); 
                    CloseServiceHandle(schSCManager);
                    return; 
                }
            }
        }
    
        // Attempt to start the service.
    
        if (!StartService(
                schService,  // handle to service 
                0,           // number of arguments 
                NULL) )      // no arguments 
        {
            
    	printf("StartService failed (%d)\n", GetLastError());
            CloseServiceHandle(schService); 
            CloseServiceHandle(schSCManager);
            return; 
        }
        else printf("Service start pending...\n"); 
    
        // Check the status until the service is no longer start pending. 
     
        if (!QueryServiceStatusEx( 
                schService,                     // handle to service 
                SC_STATUS_PROCESS_INFO,         // info level
                (LPBYTE) &ssStatus,             // address of structure
                sizeof(SERVICE_STATUS_PROCESS), // size of structure
                &dwBytesNeeded ) )              // if buffer too small
        {
            
    	printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
            CloseServiceHandle(schService); 
            CloseServiceHandle(schSCManager);
            return; 
        }
     
        // Save the tick count and initial checkpoint.
    
        dwStartTickCount = GetTickCount();
        dwOldCheckPoint = ssStatus.dwCheckPoint;
    
        while (ssStatus.dwCurrentState == SERVICE_START_PENDING) 
        { 
            // Do not wait longer than the wait hint. A good interval is 
            // one-tenth the wait hint, but no less than 1 second and no 
            // more than 10 seconds. 
     
            dwWaitTime = ssStatus.dwWaitHint / 10;
    
            if( dwWaitTime < 1000 )
                dwWaitTime = 1000;
            else if ( dwWaitTime > 10000 )
                dwWaitTime = 10000;
    
            Sleep( dwWaitTime );
    
            // Check the status again. 
     
            if (!QueryServiceStatusEx( 
                schService,             // handle to service 
                SC_STATUS_PROCESS_INFO, // info level
                (LPBYTE) &ssStatus,             // address of structure
                sizeof(SERVICE_STATUS_PROCESS), // size of structure
                &dwBytesNeeded ) )              // if buffer too small
            {
               
    	    printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
                break; 
            }
     
            if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
            {
                // Continue to wait and check.
    
                dwStartTickCount = GetTickCount();
                dwOldCheckPoint = ssStatus.dwCheckPoint;
            }
            else
            {
                if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
                {
                    // No progress made within the wait hint.
                    break;
                }
            }
        } 
    
        // Determine whether the service is running.
    
        if (ssStatus.dwCurrentState == SERVICE_RUNNING) 
        {
            printf("Service started successfully.\n"); 
        }
        else 
        { 
            printf("Service not started. \n");
            printf("  Current State: %d\n", ssStatus.dwCurrentState); 
            printf("  Exit Code: %d\n", ssStatus.dwWin32ExitCode); 
            printf("  Check Point: %d\n", ssStatus.dwCheckPoint); 
            printf("  Wait Hint: %d\n", ssStatus.dwWaitHint); 
        } 
    
        CloseServiceHandle(schService); 
        CloseServiceHandle(schSCManager);
    }
    
    
    
    //
    // Purpose: 
    //   Stops the service.
    //
    // Parameters:
    //   None
    // 
    // Return value:
    //   None
    //
    VOID __stdcall DoStopSvc()
    {
        SERVICE_STATUS_PROCESS ssp;
        DWORD dwStartTime = GetTickCount();
        DWORD dwBytesNeeded;
        DWORD dwTimeout = 30000; // 30-second time-out
        DWORD dwWaitTime;
    
        // Get a handle to the SCM database. 
     
        schSCManager = OpenSCManager( 
            NULL,                    // local computer
            NULL,                    // ServicesActive database 
            SC_MANAGER_ALL_ACCESS);  // full access rights 
     
        if (NULL == schSCManager) 
        {
    		
            printf("OpenSCManager failed (%d)\n", GetLastError());
            return;
        }
    
        // Get a handle to the service.
    
        schService = OpenService( 
            schSCManager,         // SCM database 
            szSvcName,            // name of service 
            SERVICE_STOP | 
            SERVICE_QUERY_STATUS | 
            SERVICE_ENUMERATE_DEPENDENTS);  
     
        if (schService == NULL)
        { 
            
            printf("OpenService failed (%d)\n", GetLastError()); 
            CloseServiceHandle(schSCManager);
            return;
        }    
    
        // Make sure the service is not already stopped.
    
        if ( !QueryServiceStatusEx( 
                schService, 
                SC_STATUS_PROCESS_INFO,
                (LPBYTE)&ssp, 
                sizeof(SERVICE_STATUS_PROCESS),
                &dwBytesNeeded ) )
        {
           
            printf("QueryServiceStatusEx failed (%d)\n", GetLastError()); 
            goto stop_cleanup;
        }
    
        if ( ssp.dwCurrentState == SERVICE_STOPPED )
        {
            printf("Service is already stopped.\n");
            goto stop_cleanup;
        }
    
        // If a stop is pending, wait for it.
    
        while ( ssp.dwCurrentState == SERVICE_STOP_PENDING ) 
        {
            printf("Service stop pending...\n");
    
            // Do not wait longer than the wait hint. A good interval is 
            // one-tenth of the wait hint but not less than 1 second  
            // and not more than 10 seconds. 
     
            dwWaitTime = ssp.dwWaitHint / 10;
    
            if( dwWaitTime < 1000 )
                dwWaitTime = 1000;
            else if ( dwWaitTime > 10000 )
                dwWaitTime = 10000;
    
            Sleep( dwWaitTime );
    
            if ( !QueryServiceStatusEx( 
                     schService, 
                     SC_STATUS_PROCESS_INFO,
                     (LPBYTE)&ssp, 
                     sizeof(SERVICE_STATUS_PROCESS),
                     &dwBytesNeeded ) )
            {
                
    	   printf("QueryServiceStatusEx failed (%d)\n", GetLastError()); 
                goto stop_cleanup;
            }
    
            if ( ssp.dwCurrentState == SERVICE_STOPPED )
            {
                
    	    printf("Service stopped successfully.\n");
                goto stop_cleanup;
            }
    
            if ( GetTickCount() - dwStartTime > dwTimeout )
            {
                printf("Service stop timed out.\n");
                goto stop_cleanup;
            }
        }
    
        // If the service is running, dependencies must be stopped first.
    
        StopDependentServices();
    
        // Send a stop code to the service.
    
        if ( !ControlService( 
                schService, 
                SERVICE_CONTROL_STOP, 
                (LPSERVICE_STATUS) &ssp ) )
        {
           
    	printf( "ControlService failed (%d)\n", GetLastError() );
            goto stop_cleanup;
        }
    
        // Wait for the service to stop.
    
        while ( ssp.dwCurrentState != SERVICE_STOPPED ) 
        {
            Sleep( ssp.dwWaitHint );
            if ( !QueryServiceStatusEx( 
                    schService, 
                    SC_STATUS_PROCESS_INFO,
                    (LPBYTE)&ssp, 
                    sizeof(SERVICE_STATUS_PROCESS),
                    &dwBytesNeeded ) )
            {
                
    	    printf( "QueryServiceStatusEx failed (%d)\n", GetLastError() );
                goto stop_cleanup;
            }
    
            if ( ssp.dwCurrentState == SERVICE_STOPPED )
                break;
    
            if ( GetTickCount() - dwStartTime > dwTimeout )
            {
                printf( "Wait timed out\n" );
                goto stop_cleanup;
            }
        }
        printf("Service stopped successfully\n");
    
    stop_cleanup:
        CloseServiceHandle(schService); 
        CloseServiceHandle(schSCManager);
    }
    
    BOOL __stdcall StopDependentServices()
    {
        DWORD i;
        DWORD dwBytesNeeded;
        DWORD dwCount;
    
        LPENUM_SERVICE_STATUS   lpDependencies = NULL;
        ENUM_SERVICE_STATUS     ess;
        SC_HANDLE               hDepService;
        SERVICE_STATUS_PROCESS  ssp;
    
        DWORD dwStartTime = GetTickCount();
        DWORD dwTimeout = 30000; // 30-second time-out
    
        // Pass a zero-length buffer to get the required buffer size.
        if ( EnumDependentServices( schService, SERVICE_ACTIVE, 
             lpDependencies, 0, &dwBytesNeeded, &dwCount ) ) 
        {
             // If the Enum call succeeds, then there are no dependent
             // services, so do nothing.
             return TRUE;
        } 
        else 
        {
            if ( GetLastError() != ERROR_MORE_DATA )
                return FALSE; // Unexpected error
    
            // Allocate a buffer for the dependencies.
            lpDependencies = (LPENUM_SERVICE_STATUS) HeapAlloc( 
                GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesNeeded );
      
            if ( !lpDependencies )
                return FALSE;
    
            __try {
                // Enumerate the dependencies.
                if ( !EnumDependentServices( schService, SERVICE_ACTIVE, 
                    lpDependencies, dwBytesNeeded, &dwBytesNeeded,
                    &dwCount ) )
                return FALSE;
    
                for ( i = 0; i < dwCount; i++ ) 
                {
                    ess = *(lpDependencies + i);
                    // Open the service.
                    hDepService = OpenService( schSCManager, 
                       ess.lpServiceName, 
                       SERVICE_STOP | SERVICE_QUERY_STATUS );
    
                    if ( !hDepService )
                       return FALSE;
    
                    __try {
                        // Send a stop code.
                        if ( !ControlService( hDepService, 
                                SERVICE_CONTROL_STOP,
                                (LPSERVICE_STATUS) &ssp ) )
                        return FALSE;
    
                        // Wait for the service to stop.
                        while ( ssp.dwCurrentState != SERVICE_STOPPED ) 
                        {
                            Sleep( ssp.dwWaitHint );
                            if ( !QueryServiceStatusEx( 
                                    hDepService, 
                                    SC_STATUS_PROCESS_INFO,
                                    (LPBYTE)&ssp, 
                                    sizeof(SERVICE_STATUS_PROCESS),
                                    &dwBytesNeeded ) )
                            return FALSE;
    
                            if ( ssp.dwCurrentState == SERVICE_STOPPED )
                                break;
    
                            if ( GetTickCount() - dwStartTime > dwTimeout )
                                return FALSE;
                        }
                    } 
                    __finally 
                    {
                        // Always release the service handle.
                        CloseServiceHandle( hDepService );
                    }
                }
            } 
            __finally 
            {
                // Always free the enumeration buffer.
                HeapFree( GetProcessHeap(), 0, lpDependencies );
            }
        } 
        return TRUE;
    }
    Bon, certains pourront ne pas apprécier ce code car il contient des goto mais on peut changer ça facilement en ajoutant des tests sur le retour de GetLastError() et en transitant le bon avancement dans une variable booléenne ...
    Amusez vous bien ^^

  7. #7
    Membre du Club Avatar de masterx_goldman
    Inscrit en
    Mai 2008
    Messages
    164
    Détails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 164
    Points : 51
    Points
    51
    Par défaut
    Précis et concis , merci bacelar

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. comment créer un service windows sans prérequi .NET framework ?
    Par masterx_goldman dans le forum Framework .NET
    Réponses: 7
    Dernier message: 14/04/2009, 16h40
  2. Réponses: 1
    Dernier message: 27/10/2005, 09h26
  3. Redémarrer un service Windows...
    Par RC10GT_MGT dans le forum API, COM et SDKs
    Réponses: 5
    Dernier message: 22/08/2005, 14h42
  4. gestion des Services Windows sans .NET
    Par zedoo dans le forum MFC
    Réponses: 1
    Dernier message: 16/05/2005, 23h52
  5. [WinService][C#] Comment déployer un service windows ?
    Par sokette dans le forum Windows Forms
    Réponses: 5
    Dernier message: 27/04/2005, 16h38

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo