Lars Martin Hambro <lars_martin4 AT hotmail DOT com>
[reactos.git] / reactos / base / applications / mscutils / servman / start.c
1 /*
2 * PROJECT: ReactOS Services
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: base/applications/mscutils/servman/start.c
5 * PURPOSE: Start a service
6 * COPYRIGHT: Copyright 2005-2007 Ged Murphy <gedmurphy@reactos.org>
7 *
8 */
9
10 #include "precomp.h"
11
12 static BOOL
13 DoStartService(PMAIN_WND_INFO Info,
14 HWND hProgDlg)
15 {
16 SC_HANDLE hSCManager;
17 SC_HANDLE hSc;
18 SERVICE_STATUS_PROCESS ServiceStatus;
19 DWORD BytesNeeded = 0;
20 BOOL bRet = FALSE;
21 BOOL bDispErr = TRUE;
22
23 hSCManager = OpenSCManager(NULL,
24 NULL,
25 SC_MANAGER_ALL_ACCESS);
26 if (hSCManager != NULL)
27 {
28 hSc = OpenService(hSCManager,
29 Info->pCurrentService->lpServiceName,
30 SERVICE_ALL_ACCESS);
31 if (hSc != NULL)
32 {
33 if (StartService(hSc,
34 0,
35 NULL))
36 {
37 bDispErr = FALSE;
38
39 if (QueryServiceStatusEx(hSc,
40 SC_STATUS_PROCESS_INFO,
41 (LPBYTE)&ServiceStatus,
42 sizeof(SERVICE_STATUS_PROCESS),
43 &BytesNeeded))
44 {
45 DWORD dwStartTickCount = GetTickCount();
46 DWORD dwOldCheckPoint = ServiceStatus.dwCheckPoint;
47 DWORD dwMaxWait = 2000 * 60; // wait for 2 mins
48
49 IncrementProgressBar(hProgDlg);
50
51 while (ServiceStatus.dwCurrentState != SERVICE_RUNNING)
52 {
53 DWORD dwWaitTime = ServiceStatus.dwWaitHint / 10;
54
55 if (!QueryServiceStatusEx(hSc,
56 SC_STATUS_PROCESS_INFO,
57 (LPBYTE)&ServiceStatus,
58 sizeof(SERVICE_STATUS_PROCESS),
59 &BytesNeeded))
60 {
61 break;
62 }
63
64 if (ServiceStatus.dwCheckPoint > dwOldCheckPoint)
65 {
66 /* The service is making progress, increment the progress bar */
67 IncrementProgressBar(hProgDlg);
68 dwStartTickCount = GetTickCount();
69 dwOldCheckPoint = ServiceStatus.dwCheckPoint;
70 }
71 else
72 {
73 if(GetTickCount() >= dwStartTickCount + dwMaxWait)
74 {
75 /* give up */
76 break;
77 }
78 }
79
80 if(dwWaitTime < 200)
81 dwWaitTime = 200;
82 else if (dwWaitTime > 10000)
83 dwWaitTime = 10000;
84
85 Sleep(dwWaitTime);
86 }
87 }
88 }
89
90 CloseServiceHandle(hSc);
91 }
92
93 CloseServiceHandle(hSCManager);
94 }
95
96 if (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
97 {
98 CompleteProgressBar(hProgDlg);
99 Sleep(500);
100 bRet = TRUE;
101 }
102 else
103 {
104 if (bDispErr)
105 GetError();
106 else
107 DisplayString(_T("The service failed to start"));
108 }
109
110 return bRet;
111 }
112
113
114 BOOL
115 DoStart(PMAIN_WND_INFO Info)
116 {
117 HWND hProgDlg;
118 BOOL bRet = FALSE;
119
120 hProgDlg = CreateProgressDialog(Info->hMainWnd,
121 Info->pCurrentService->lpServiceName,
122 IDS_PROGRESS_INFO_START);
123
124 if (hProgDlg)
125 {
126 IncrementProgressBar(hProgDlg);
127
128 bRet = DoStartService(Info,
129 hProgDlg);
130
131 DestroyWindow(hProgDlg);
132 }
133
134 return bRet;
135 }