64,282
社区成员
发帖
与我相关
我的任务
分享
//*********************************************************
//Function: StopService
//Description: Stop the service by calling the API ControlService
//Calls:
//Called By:
//Table Accessed:
//Table Updated:
//Input:
//Output:
//Return:
//Others:
//History:
// <author>philip <time>2010-11-17 <version> <desc>
//*********************************************************
BOOL StopService()
{
// Get a handle to the SCM database.
SC_HANDLE hSCM = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == hSCM)
{
cout << "StopService_OpenSCManager: " << GetLastError() << endl;
return FALSE;
}
// Get a handle to the service.
SC_HANDLE hService = OpenService(
hSCM, // SCM database
SERVICE_FRAME_NAME, // name of service
SERVICE_ALL_ACCESS);
if (NULL == hService)
{
cout << "StopService_OpenService: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
return FALSE;
}
// Make sure the service is not already stopped.
SERVICE_STATUS_PROCESS ssp;
DWORD dwStartTime = GetTickCount();
DWORD dwBytesNeeded;
DWORD dwTimeout = 30000; // 30-second time-out
if ( !QueryServiceStatusEx(
hService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
cout << "StopService_QueryServiceStatusEx: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
if ( ssp.dwCurrentState == SERVICE_STOPPED )
{
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return TRUE;
}
// If a stop is pending, wait for it.
while ( ssp.dwCurrentState == SERVICE_STOP_PENDING )
{
Sleep( ssp.dwWaitHint );
if ( !QueryServiceStatusEx(
hService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
cout << "StopService_QueryServiceStatusEx: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
if ( ssp.dwCurrentState == SERVICE_STOPPED )
{
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return TRUE;
}
if ( GetTickCount() - dwStartTime > dwTimeout )
{
cout << "StopService: Service stop timed out." << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
}
// If the service is running, dependencies must be stopped first.
if ( !StopDependentServices(hSCM, hService) )
{
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
// Send a stop code to the service.
if (!ControlService(hService, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS) &ssp))
{
cout << "StopService_ControlService: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
// Wait for the service to stop.
while ( ssp.dwCurrentState != SERVICE_STOPPED )
{
Sleep( ssp.dwWaitHint );
if ( !QueryServiceStatusEx(
hService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
cout << "StopService_QueryServiceStatusEx: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
if ( ssp.dwCurrentState == SERVICE_STOPPED )
{
break;
}
if ( GetTickCount() - dwStartTime > dwTimeout )
{
cout << "StopService: Service stop timed out." << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
}
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return TRUE;
}
//*********************************************************
//Function: UninstallService
//Description: Uninstall the service
//Calls:
//Called By:
//Table Accessed:
//Table Updated:
//Input:
//Output:
//Return:
//Others:
//History:
// <author>philip <time>2010-11-17 <version> <desc>
//*********************************************************
BOOL UninstallService()
{
if (!IsAlreadyInstalled())
return TRUE;
// Get a handle to the SCM database.
SC_HANDLE hSCM = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == hSCM)
{
cout << "UninstallService_OpenSCManager: " << GetLastError() << endl;
return FALSE;
}
// Get a handle to the service.
SC_HANDLE hService = OpenService(
hSCM, // SCM database
SERVICE_FRAME_NAME, // name of service
SERVICE_ALL_ACCESS);
if (NULL == hService)
{
cout << "UninstallService_OpenService: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
return FALSE;
}
// Make sure the service is already stopped.
SERVICE_STATUS_PROCESS ssp;
DWORD dwStartTime = GetTickCount();
DWORD dwBytesNeeded;
DWORD dwTimeout = 30000; // 30-second time-out
if ( !QueryServiceStatusEx(
hService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
cout << "UninstallService_QueryServiceStatusEx: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
if ( ssp.dwCurrentState != SERVICE_STOPPED )
{
// If the service is running, dependencies must be stopped first.
if ( !StopDependentServices(hSCM, hService) )
{
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
// Send a stop code to the service.
if (!ControlService(hService, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS) &ssp))
{
cout << "UninstallService_ControlService: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
// Wait for the service to stop.
while ( ssp.dwCurrentState != SERVICE_STOPPED )
{
Sleep( ssp.dwWaitHint );
if ( !QueryServiceStatusEx(
hService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
cout << "UninstallService_QueryServiceStatusEx: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
if ( ssp.dwCurrentState == SERVICE_STOPPED )
{
break;
}
if ( GetTickCount() - dwStartTime > dwTimeout )
{
cout << "UninstallService: Service stop timed out." << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
}
}
// Delete the service
if (!DeleteService(hService))
{
cout << "UninstallService_DeleteService: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return TRUE;
}
//*********************************************************
//Function: StartService
//Description: Start the service by calling the API StartService
//Calls:
//Called By:
//Table Accessed:
//Table Updated:
//Input:
//Output:
//Return:
//Others: It and API StartService have the same name but different parameters
//History:
// <author>philip <time>2010-11-17 <version> <desc>
//*********************************************************
BOOL StartService()
{
// Get a handle to the SCM database.
SC_HANDLE hSCM = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == hSCM)
{
cout << "StartServiceCustom_OpenSCManager: " << GetLastError() << endl;
return FALSE;
}
// Get a handle to the service.
SC_HANDLE hService = OpenService(
hSCM, // SCM database
SERVICE_FRAME_NAME, // name of service
SERVICE_ALL_ACCESS);
if (NULL == hService)
{
cout << "StartServiceCustom_OpenService: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
return FALSE;
}
// Attempt to start the service.
if (!StartService(hService, 0, 0))
{
cout << "StartServiceCustom_StartService: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
// Check the status until the service is no longer start pending.
SERVICE_STATUS_PROCESS ssStatus;
DWORD dwOldCheckPoint;
DWORD dwStartTickCount;
DWORD dwWaitTime;
DWORD dwBytesNeeded;
if (!QueryServiceStatusEx(
hService, // 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
{
cout << "StartServiceCustom_QueryServiceStatusEx: " << GetLastError() << endl;
return FALSE;
}
// 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(
hService, // 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
{
cout << "StartServiceCustom_QueryServiceStatusEx: " << GetLastError() << endl;
break;
}
if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
{
// The service is making progress.
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)
{
cout << "Service not started." << endl;
cout << " Current State: " << ssStatus.dwCurrentState << endl;
cout << " Exit Code: " << ssStatus.dwWin32ExitCode << endl;
cout << " Check Point: " << ssStatus.dwCheckPoint << endl;
cout << " Wait Hint: " << ssStatus.dwWaitHint << endl;
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return FALSE;
}
CloseServiceHandle(hSCM);
CloseServiceHandle(hService);
return TRUE;
}
//*********************************************************
//Function: StopDependentServices
//Description: Prior to stop the service, dependencies must be stopped first.
//Calls:
//Called By:
//Table Accessed:
//Table Updated:
//Input:
//Output:
//Return:
//Others:
//History:
// <author>philip <time>2010-11-17 <version> <desc>
//*********************************************************
BOOL StopDependentServices(SC_HANDLE hSCM, SC_HANDLE hService)
{
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( hService, SERVICE_ACTIVE, lpDependencies, 0, &dwBytesNeeded, &dwCount ) )
{
// If the Enum call succeeds, then there are no dependent services, so do nothing.
return TRUE;
}
else
{
// Unexpected error
if ( GetLastError() != ERROR_MORE_DATA )
{
return FALSE;
}
// Allocate a buffer for the dependencies.
lpDependencies = (LPENUM_SERVICE_STATUS) HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesNeeded );
if ( !lpDependencies )
{
return FALSE;
}
// Enumerate the dependencies.
if ( !EnumDependentServices( hService, SERVICE_ACTIVE, lpDependencies, dwBytesNeeded, &dwBytesNeeded, &dwCount ) )
{
cout << "StopDependentServices_EnumDependentServices: " << GetLastError() << endl;
HeapFree( GetProcessHeap(), 0, lpDependencies );
return FALSE;
}
//Attempt to stop dependent services
for (DWORD i = 0; i < dwCount; i++ )
{
ess = *(lpDependencies + i);
// Get a handle to the service.
hDepService = OpenService( hSCM,
ess.lpServiceName,
SERVICE_STOP | SERVICE_QUERY_STATUS );
if ( !hDepService )
{
cout << "StopDependentServices_OpenService: " << GetLastError() << endl;
HeapFree( GetProcessHeap(), 0, lpDependencies );
return FALSE;
}
// Send a stop code.
if ( !ControlService( hDepService,
SERVICE_CONTROL_STOP,
(LPSERVICE_STATUS) &ssp ) )
{
cout << "StopDependentServices_OpenService: " << GetLastError() << endl;
CloseServiceHandle(hDepService);
HeapFree( GetProcessHeap(), 0, lpDependencies );
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 ) )
{
cout << "StopDependentServices_QueryServiceStatusEx: " << GetLastError() << endl;
CloseServiceHandle(hDepService);
HeapFree( GetProcessHeap(), 0, lpDependencies );
return FALSE;
}
if ( ssp.dwCurrentState == SERVICE_STOPPED )
break;
if ( GetTickCount() - dwStartTime > dwTimeout )
{
cout << "StopDependentServices: Service stop timed out." << endl;
CloseServiceHandle(hDepService);
HeapFree( GetProcessHeap(), 0, lpDependencies );
return FALSE;
}
}
// Always release the service handle.
CloseServiceHandle( hDepService );
}
// Always free the enumeration buffer.
HeapFree( GetProcessHeap(), 0, lpDependencies );
}
return TRUE;
}
#include <Windows.h>
#include <iostream>
#include <tchar.h>
#include <strsafe.h>
#ifdef _UNICODE
#include <shlobj.h>
#endif
#ifndef _UNICODE
#include <Dbghelp.h>
#pragma comment(lib, "Dbghelp.lib")
#endif
using namespace std;
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hServiceStatus;
HANDLE killServiceEvent;
HANDLE threadClosedNormallyEvent[3];
HANDLE hServiceFirstThread;
HANDLE hServiceSecondThread;
HANDLE hServiceThirdThread;
BOOL nServiceStopFlag = FALSE;
BOOL nServicePauseFlag = FALSE;
#define SERVICE_FRAME_NAME _T("ReportAgent") //service name
#define LOGFILE _T("C:\\MyService\\memstatus.txt") //the full path to the log file
BOOL IsAlreadyInstalled();
BOOL InstallService();
BOOL StartService();
BOOL StopDependentServices(SC_HANDLE hSCM, SC_HANDLE hService);
BOOL StopService();
BOOL UninstallService();
VOID ReportSvcStatus( DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwWaitHint);
VOID ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv);
VOID WINAPI ServiceCtrl(DWORD dwCode);
BOOL WriteToLog(LPCTSTR sourceFile, LPCTSTR functionName, DWORD errorCode);
DWORD ServiceExecutionFirstThread(LPDWORD param);
DWORD ServiceExecutionSecondThread(LPDWORD param);
DWORD ServiceExecutionThirdThread(LPDWORD param);
BOOL StartServiceThread();
int _tmain(int argc, TCHAR* argv[])
{
SERVICE_TABLE_ENTRY DispatchTable[] =
{
{SERVICE_FRAME_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain},
{NULL , NULL }
};
if (argc > 1)
{
if (_tcsicmp(argv[1], _T("/install")) == 0)
{
if ( InstallService() != TRUE )
{
return 1;
}
}
else if (_tcsicmp(argv[1], _T("/uninstall")) == 0)
{
if ( UninstallService() != TRUE )
{
return 1;
}
}
else if (_tcsicmp(argv[1], _T("/start")) == 0)
{
if ( StartService() != TRUE )
{
return 1;
}
}
else if (_tcsicmp(argv[1], _T("/stop")) == 0)
{
if ( StopService() != TRUE )
{
return 1;
}
}
}
else
{
if (!StartServiceCtrlDispatcher(DispatchTable))
{
cout <<"StartServiceCtrlDispatcher: " << GetLastError() << endl;
return 1;
}
}
return 0;
}
//*********************************************************
//Function: IsAlreadyInstalled
//Description: Determine whether the service is already installed or not
//Calls:
//Called By:
//Table Accessed:
//Table Updated:
//Input:
//Output:
//Return:
//Others:
//History:
// <author>philip <time>2010-11-17 <version> <desc>
//*********************************************************
BOOL IsAlreadyInstalled()
{
BOOL bResult = FALSE;
// Get a handle to the SCM database.
SC_HANDLE hSCM = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (hSCM != NULL)
{
// Get a handle to the service.
SC_HANDLE hService = OpenService(
hSCM, // SCM database
SERVICE_FRAME_NAME, // name of service
SERVICE_QUERY_CONFIG);
if (hService != NULL)
{
bResult = TRUE;
CloseServiceHandle(hService);
}
CloseServiceHandle(hSCM);
}
return bResult;
}
//*********************************************************
//Function: InstallService
//Description: Install the service
//Calls:
//Called By:
//Table Accessed:
//Table Updated:
//Input:
//Output:
//Return:
//Others:
//History:
// <author>philip <time>2010-11-17 <version> <desc>
//*********************************************************
BOOL InstallService()
{
if ( IsAlreadyInstalled() )
return TRUE;
// Get module directory
TCHAR szPath[MAX_PATH];
memset( szPath, 0, MAX_PATH * sizeof(TCHAR) );
if ( !GetModuleFileName( NULL, szPath, MAX_PATH ) )
{
cout << "InstallService_GetModuleFileName: " << GetLastError() << endl;
return FALSE;
}
// Get a handle to the SCM database.
SC_HANDLE hSCM = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == hSCM)
{
cout << "InstallService_OpenSCManager: " << GetLastError() << endl;
return FALSE;
}
// Create the service.
SC_HANDLE hService = CreateService(
hSCM, // SCManager database
SERVICE_FRAME_NAME, // name of service
SERVICE_FRAME_NAME, // service name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICE_AUTO_START, // start type
SERVICE_ERROR_NORMAL, // error control type
szPath, // path to service's binary
NULL, // no load ordering group
NULL, // no tag identifier
NULL, // no dependencies
NULL, // LocalSystem account
NULL); // no password
if (NULL == hService)
{
cout << "InstallService_CreateService: " << GetLastError() << endl;
CloseServiceHandle(hSCM);
return FALSE;
}
// Change the service service type.
if ( !ChangeServiceConfig(
hService, // handle of service
SERVICE_WIN32_OWN_PROCESS
| SERVICE_INTERACTIVE_PROCESS, // service type
SERVICE_NO_CHANGE, // service start type: no change
SERVICE_NO_CHANGE, // error control: no change
NULL, // binary path: no change
NULL, // load order group: no change
NULL, // tag ID: no change
NULL, // dependencies: no change
NULL, // account name: no change
NULL, // password: no change
NULL) ) // display name: no change
{
cout << "InstallService_ChangeServiceConfig: " << GetLastError() << endl;
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return FALSE;
}
// Change the service description.
SERVICE_DESCRIPTION sd;
LPTSTR szDesc = _T("This is a test service");
sd.lpDescription = szDesc;
if( !ChangeServiceConfig2(
hService, // handle to service
SERVICE_CONFIG_DESCRIPTION, // change: description
&sd) ) // new description
{
cout << "InstallService_ChangeServiceConfig2: " << GetLastError() << endl;
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return FALSE;
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return TRUE;
}
void OpenServerService()
{
CString ErrorString;
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCManager == NULL)
{
ErrorString.Format(L"打开服务管理器失败:%d", GetLastError());
LogList.AddString(ErrorString);
return;
}
SC_HANDLE hService = OpenService(hSCManager, L"SecureProxyServer", SERVICE_ALL_ACCESS);
if (hService == NULL)
{
ErrorString.Format(L"打开服务失败:%d", GetLastError());
LogList.AddString(ErrorString);
return;
}
if (! StartService(hService, 0, NULL))
{
ErrorString.Format(L"开启服务失败:%d", GetLastError());
LogList.AddString(ErrorString);
return;
}
if (ssStatus.dwCurrentState == SERVICE_RUNNING)
AfxMessageBox(L"服务器启动成功!");
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
}
void StopServerService()
{
CString ErrorString;
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCManager == NULL)
{
ErrorString.Format(L"打开服务管理器失败:%d", GetLastError());
AfxMessageBox(ErrorString);
return;
}
SC_HANDLE hService = OpenService(hSCManager, L"SecureProxyServer", SERVICE_ALL_ACCESS);
if (hService == NULL)
{
ErrorString.Format(L"打开服务失败:%d", GetLastError());
AfxMessageBox(ErrorString);
return;
}
SERVICE_STATUS ss = {0};
if (! ControlService(hService, SERVICE_CONTROL_STOP, &ss))
{
ErrorString.Format(L"暂停服务失败:%d", GetLastError());
AfxMessageBox(ErrorString);
return;
}
AfxMessageBox(L"服务器暂停成功!");
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
}
wchar_t g_service_name[] = L"SecureProxyServer"; // 服务名称
wchar_t g_service_discription[] = L"安全代理服务器程序"; // 服务描述
SERVICE_STATUS g_service_status;
SERVICE_STATUS_HANDLE g_status_handle;
DWORD g_error = 0;
HANDLE g_wait_event = NULL;
BOOL run()
{
SERVICE_TABLE_ENTRY DispatchTable[] = {{ g_service_name, (LPSERVICE_MAIN_FUNCTION)ServiceMain }, { NULL, NULL }};
return StartServiceCtrlDispatcher(DispatchTable);
}
BOOL install()
{
wchar_t path[MAX_PATH] = {0};
if (! GetModuleFileName(NULL, path, MAX_PATH))
{
ServerLog.dprintf(InfoLevel, "Cannot install service (%d)\n", GetLastError());
return FALSE;
}
SC_HANDLE hSCManager;
hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCManager == NULL)
{
ServerLog.dprintf(InfoLevel, "OpenSCManager failed (%d)\n", GetLastError());
return FALSE;
}
SC_HANDLE hService;
hService = CreateService( hSCManager,
g_service_name,
g_service_name,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS ,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
path,
L"ShellSvcGroup",
NULL,
NULL,
NULL,
NULL
);
if (hService == NULL)
{
CloseServiceHandle( hSCManager );
return FALSE;
}
SERVICE_DESCRIPTION sd = {0};
sd.lpDescription = g_service_discription;
ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sd);
CloseServiceHandle( hService );
CloseServiceHandle( hSCManager );
return TRUE;
}
BOOL uninstall()
{
SC_HANDLE hSCManager;
hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCManager == NULL)
{
ServerLog.dprintf(InfoLevel, "OpenSCManager failed (%d)\n", GetLastError());
return FALSE;
}
SC_HANDLE hService;
hService = OpenService(hSCManager, g_service_name, SERVICE_ALL_ACCESS);
if (hService == NULL )
{
ServerLog.dprintf(InfoLevel, "OpenService failed (%d)\n", GetLastError());
return FALSE;
}
SERVICE_STATUS ss = {0};
if (! ControlService(hService, SERVICE_CONTROL_STOP, &ss))
ServerLog.dprintf(InfoLevel, "ControlService failed (%d)\n", GetLastError());
if (! DeleteService(hService))
{
ServerLog.dprintf(InfoLevel, "DeleteService failed (%d)\n", GetLastError());
return FALSE;
}
else
ServerLog.dprintf(InfoLevel, "Service deleted successfully\n");
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
return TRUE;
}
VOID WINAPI ServiceMain(DWORD argc, TCHAR *argv[])
{
g_service_status.dwServiceType = SERVICE_WIN32;
g_service_status.dwCurrentState = SERVICE_START_PENDING;
g_service_status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN ;
g_service_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
g_service_status.dwServiceSpecificExitCode = 0;
g_service_status.dwCheckPoint = 1;
g_service_status.dwWaitHint = 2000;
DWORD dwWait;
g_status_handle = RegisterServiceCtrlHandlerEx(g_service_name, ServiceCtrlHandlerEx, &dwWait); // 注册服务状态改变时的回调函数
if (g_status_handle == SERVICE_STATUS_HANDLE(NULL))
{
ServerLog.dprintf(InfoLevel, "RegisterServiceCtrlHandler failed %d\n", GetLastError());
return;
}
if (! SetServiceStatus(g_status_handle, &g_service_status))
{
ServerLog.dprintf(InfoLevel, "SetServiceStatus pending failed %d\n", GetLastError());
ReportStatusToSCMgr(SERVICE_STOPPED, g_error, 0);
return;
}
g_wait_event = CreateEvent(NULL, TRUE, FALSE, NULL);
if (g_wait_event == NULL)
{
ServerLog.dprintf(InfoLevel, "CreateEvent failed %d\n", GetLastError());
ReportStatusToSCMgr(SERVICE_STOPPED, g_error, 0);
return;
}
这里,填上你的主函数,不要太复杂,后面还要报告服务状态
main();
// 报告服务启动成功
if (! ReportStatusToSCMgr(SERVICE_RUNNING, NO_ERROR, 2))
{
ServerLog.dprintf(InfoLevel, "ReportStatusToSCMgr failed %d\n", GetLastError());
ReportStatusToSCMgr( SERVICE_STOPPED, g_error, 0);
return;
}
dwWait = WaitForSingleObject(g_wait_event, INFINITE);
if (g_wait_event != NULL)
CloseHandle(g_wait_event);
if (g_status_handle != NULL )
ReportStatusToSCMgr( SERVICE_STOPPED, g_error, 0);
}
/*服务状态处理*/
DWORD WINAPI ServiceCtrlHandlerEx( DWORD control, DWORD eventType, LPVOID lpEnentData, LPVOID lpContext )
{
DWORD dwState = SERVICE_RUNNING;
switch (control)
{
case SERVICE_CONTROL_PAUSE:
if (g_service_status.dwCurrentState == SERVICE_RUNNING )
{
//PauseService();
dwState = SERVICE_PAUSED;
}
break;
case SERVICE_CONTROL_CONTINUE:
if (g_service_status.dwCurrentState == SERVICE_PAUSED )
{
//ResumeService();
dwState = SERVICE_RUNNING;
}
break;
case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP :
dwState = SERVICE_STOP_PENDING;
(VOID)ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, 1);
SetEvent(g_wait_event);
return 0;
case SERVICE_CONTROL_INTERROGATE:
break;
default :
break;
}
(VOID)ReportStatusToSCMgr(dwState, NO_ERROR, -1);
return 0;
}
/*服务状态控制器处理函数*/
BOOL ReportStatusToSCMgr(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwCheckPoint)
{
if (DebugMode)
return TRUE;
BOOL fResult;
if (dwCurrentState == SERVICE_START_PENDING)
g_service_status.dwControlsAccepted = 0;
else
g_service_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
if (dwCurrentState >= 0)
g_service_status.dwCurrentState = dwCurrentState;
g_service_status.dwWin32ExitCode = dwWin32ExitCode;
if (dwCheckPoint < 0 )
g_service_status.dwCheckPoint++;
else
g_service_status.dwCheckPoint = dwCheckPoint;
if (! (fResult = SetServiceStatus(g_status_handle, &g_service_status)))
StopService( L"SetServiceStatus" );
return fResult != 0;
}
/*停止服务*/
void StopService(LPTSTR lpszMsg)
{
TCHAR chMsg[256];
HANDLE hEventSource;
LPTSTR lpszStrings[2];
g_error = GetLastError();
hEventSource = RegisterEventSource(NULL , g_service_name);
wprintf_s( chMsg, 256, L"%s error:%d", g_service_name, g_error);
lpszStrings[0] = chMsg;
lpszStrings[1] = lpszMsg;
if (hEventSource != NULL )
{
ReportEvent(hEventSource, EVENTLOG_ERROR_TYPE, 0, 0, NULL, 2, 0, (LPCTSTR*)lpszStrings, NULL);
(VOID)DeregisterEventSource(hEventSource);
}
SetEvent(g_wait_event);
}