Windows服务编程

我们看到有什么360主动防御服务,Google更新服务等,我们也写个简单的服务吧

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
#include <stdio.h>
#include <windows.h>

//毫秒
#define SLEEP_TIME 1000
#define FILE_PATH "D:\\test.txt"
//服务状态
SERVICE_STATUS m_ServiceState;
//服务状态句柄
SERVICE_STATUS_HANDLE m_ServiceHandle;
void WINAPI ServiceMain(int argc, char** argv);
void WINAPI ServiceCtrlHandler(DWORD Opcode);
int WriteToLog(char* str);
BOOL bRunning;

int main() {

SERVICE_TABLE_ENTRY stentry[2];
stentry[0].lpServiceName = "demo";
stentry[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTIONA)ServiceMain;
//服务的最后一项要设置为NULL
stentry[1].lpServiceName = NULL;
stentry[1].lpServiceProc = NULL;

StartServiceCtrlDispatcher(stentry);
//system("pause");
return 0;
}

//服务主函数
void WINAPI ServiceMain(int argc, char** argv) {
MEMORYSTATUS memstatus;
char str[100];
int availMem;

//服务类型和状态
m_ServiceState.dwServiceType = SERVICE_WIN32;
m_ServiceState.dwCurrentState = SERVICE_START_PENDING;
m_ServiceState.dwControlsAccepted = SERVICE_CONTROL_SHUTDOWN | SERVICE_CONTROL_STOP;
m_ServiceState.dwWin32ExitCode = 0;
m_ServiceState.dwServiceSpecificExitCode = 0;
//下面这两个基本不需要,除非服务启动时间很长
m_ServiceState.dwCheckPoint = 0;
m_ServiceState.dwWaitHint = 0;

//注册服务控制函数
m_ServiceHandle = RegisterServiceCtrlHandler("demo", (LPHANDLER_FUNCTION)ServiceCtrlHandler);
if (m_ServiceHandle == NULL) {
WriteToLog("RegisterServiceCtrlHandler failed");
return;
}
WriteToLog("RegisterServiceCtrlHandler success");

//更新服务状态
m_ServiceState.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(m_ServiceHandle, &m_ServiceState);


memset(str, '\0', 100);
bRunning = TRUE;
while (bRunning)
{
GlobalMemoryStatus(&memstatus);
availMem = memstatus.dwAvailVirtual / 1024 / 1024;
sprintf_s(str, 50 ,"available memory is %d MB, use %d %%", availMem, memstatus.dwMemoryLoad);
WriteToLog(str);
Sleep(SLEEP_TIME);

}
WriteToLog("service stop!");
}

//服务控制函数(启动,暂停等)
void WINAPI ServiceCtrlHandler(DWORD Opcode) {
switch (Opcode)
{
case SERVICE_CONTROL_STOP:
bRunning = FALSE;
m_ServiceState.dwCurrentState = SERVICE_STOPPED;
break;
case SERVICE_CONTROL_SHUTDOWN:
bRunning = FALSE;
m_ServiceState.dwCurrentState = SERVICE_STOPPED;
break;
default:
break;
}
SetServiceStatus(m_ServiceHandle, &m_ServiceState);
}

int WriteToLog(char * str)
{
FILE* pFile;
fopen_s(&pFile, FILE_PATH, "a+");
fprintf_s(pFile, "%s\n", str);
fclose(pFile);
return 0;
}

编译并生成后可以用sc命令安装

1
sc create giantbranchDemo binpath= D:\demo.exe

我们再打开服务即可看到

我们可以直接在上面的图形界面启动,也可以sc启动

启动停止与删除命令

1
2
3
sc start 
sc stop
sc delete

如果程序本身自带启动和删除可以使用下面的:

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
#include <stdio.h>
#include <windows.h>

//毫秒
#define SLEEP_TIME 1000
#define FILE_PATH "C:\\test.txt"
#define SERVICENAME "practice"
//服务状态
SERVICE_STATUS m_ServiceState;
//服务状态句柄
SERVICE_STATUS_HANDLE m_ServiceHandle;
void WINAPI ServiceMain(int argc, char** argv);
void WINAPI ServiceCtrlHandler(DWORD Opcode);
int WriteToLog(char* str);
BOOL InstallService();
void DelService();
BOOL bRunning;

int main(int argc, char** argv[]) {
SERVICE_TABLE_ENTRY stentry[2];
if (argc == 2)
{
if (!strcmp(argv[1], "-i"))
{
InstallService();
}else if (!strcmp(argv[1], "-d"))
{
DelService();
}
return 0;
}

stentry[0].lpServiceName = SERVICENAME;
stentry[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTIONA)ServiceMain;
//服务的最后一项要设置为NULL
stentry[1].lpServiceName = NULL;
stentry[1].lpServiceProc = NULL;

StartServiceCtrlDispatcher(stentry);
return 0;
}

//服务主函数
void WINAPI ServiceMain(int argc, char** argv) {
MEMORYSTATUS memstatus;
char str[100];
int availMem;

//服务类型和状态
m_ServiceState.dwServiceType = SERVICE_WIN32;
m_ServiceState.dwCurrentState = SERVICE_START_PENDING;
m_ServiceState.dwControlsAccepted = SERVICE_CONTROL_SHUTDOWN | SERVICE_CONTROL_STOP;
m_ServiceState.dwWin32ExitCode = 0;
m_ServiceState.dwServiceSpecificExitCode = 0;
//下面这两个基本不需要,除非服务启动时间很长
m_ServiceState.dwCheckPoint = 0;
m_ServiceState.dwWaitHint = 0;

//注册服务控制函数
m_ServiceHandle = RegisterServiceCtrlHandler(SERVICENAME, (LPHANDLER_FUNCTION)ServiceCtrlHandler);
if (m_ServiceHandle == NULL) {
WriteToLog("RegisterServiceCtrlHandler failed");
return;
}
WriteToLog("RegisterServiceCtrlHandler success");

//更新服务状态
m_ServiceState.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(m_ServiceHandle, &m_ServiceState);


memset(str, '\0', 100);
bRunning = TRUE;
GlobalMemoryStatus(&memstatus);
availMem = memstatus.dwAvailVirtual / 1024 / 1024;
sprintf_s(str, 50, "available memory is %d MB, use %d %%", availMem, memstatus.dwMemoryLoad);
WriteToLog(str);
WriteToLog("service is Running!");
}

//服务控制函数(启动,暂停等)
void WINAPI ServiceCtrlHandler(DWORD Opcode) {
switch (Opcode)
{
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
bRunning = FALSE;
m_ServiceState.dwWin32ExitCode = 0;
m_ServiceState.dwCurrentState = SERVICE_STOPPED;
break;
default:
break;
}
SetServiceStatus(m_ServiceHandle, &m_ServiceState);
}

int WriteToLog(char * str)
{
FILE* pFile;
fopen_s(&pFile, FILE_PATH, "a+");
fprintf_s(pFile, "%s\n", str);
fclose(pFile);
return 0;
}

BOOL InstallService()
{
char strDir[1024];
SC_HANDLE scHandler,schService;
LPCTSTR lpszBinaryPathName;
//GetCurrentDirectory(1024, strDir);
GetModuleFileName(NULL, strDir, 1024);
printf("%s\n", strDir);
lpszBinaryPathName = strDir;
scHandler = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (scHandler == NULL)
{
printf("open scmanager failed! May be you don't have the privilage?");
}
schService = CreateService(scHandler, SERVICENAME, SERVICENAME,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
lpszBinaryPathName,
NULL,
NULL,
NULL,
NULL,
NULL
);
if (schService == NULL)
{
printf("create service failed~");
return FALSE;
}
CloseServiceHandle(schService);
CloseServiceHandle(scHandler);
return TRUE;
}

void DelService()
{
SC_HANDLE scHandler;
SC_HANDLE schService;
SERVICE_STATUS status;
BOOL isSuccess;
DWORD errCode;

scHandler = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (scHandler == NULL)
{
printf("open scmanager failed! May be you don't have the privilage?");
return;
}
schService = OpenService(scHandler, SERVICENAME, SC_MANAGER_ALL_ACCESS | DELETE);
if (schService == NULL)
{
errCode = GetLastError();
printf("OpenService failed! code:%d\n", errCode);
return;
}
isSuccess = QueryServiceStatus(schService, &status);
if (!isSuccess)
{
printf("QueryServiceStatus failed!");
return;
}
if (status.dwCurrentState != SERVICE_STOPPED)
{
isSuccess = ControlService(schService, SERVICE_CONTROL_STOP, &status);
if (!isSuccess)
{
printf("Stop Service failed!");
return;
}
}
isSuccess = DeleteService(schService);
if (!isSuccess)
{
printf("DeleteService failed");
return;
}
else {
printf("DeleteService success");
}
CloseServiceHandle(scHandler);
CloseServiceHandle(schService);

}
打赏专区