VS2008 C++ windows服务

zhanghengsdnu 2010-11-10 05:13:52
公司在服务器集群软件上增加报表模块,现在需要我写框架,就是把报表模块写成一个服务,这个服务调用数据采集的dll生成原始数据文件,然后调用数据分析的dll生成分析文件,最后由数据显示的把分析文件成像。数据分析的和数据成像的通过命令交互,那么数据分析模块中需要一个线程一直运行等待接收命令,数据采集模块中一个线程一直在采集数据等等。现在是我刚写代码3个半月,不知如何利用VS2008用C++语言写windows服务,以前相关的帖子也看了,类似的知识略懂一些,但是还没动手实践过,此其一,需要写码来学习。更希望各位大大能给点通俗易懂的思路明确的指示,谢谢。最好有详细操作步骤或源码,弄通了服务的原理就好办了。分不是问题,分好挣知识无价。最多就能给100分,确实帮到我的话可以另开贴给分。再次感谢。
...全文
820 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
就想叫yoko 2010-11-19
  • 打赏
  • 举报
回复
服务说穿了也就是在WINDOWS那个服务列表里给你弄了个你的EXE的链接,
你替换掉EXE再开服务,他就执行新的EXE,一点不新奇
注意一点在服务关闭的那个地方做一下扫尾工作
直接GOOGLE一个模板套上去用就行了
注意一下在服务开启之前不要做任何操作,不然会失败,操作都放在最后那个RUN里面
herman~~ 2010-11-19
  • 打赏
  • 举报
回复
google win服务吧
zhanghengsdnu 2010-11-18
  • 打赏
  • 举报
回复

//*********************************************************
//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;
}

zhanghengsdnu 2010-11-18
  • 打赏
  • 举报
回复


//*********************************************************
//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;
}
zhanghengsdnu 2010-11-18
  • 打赏
  • 举报
回复
我也发一下我写的吧,有什么不对的还请指正。

#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;
}

wjb_yd 2010-11-18
  • 打赏
  • 举报
回复
你可以MSDN一下ControlService这个api~
wjb_yd 2010-11-18
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 zhanghengsdnu 的回复:]
引用 5 楼 wjb_yd 的回复:
哥给你段代码吧。其实MSDN上都有比较详细的解释的。

C/C++ code

wchar_t g_service_name[] = L"SecureProxyServer"; // 服务名称
wchar_t g_service_discription[] = L"安全代理服务器程序"; // 服务描述
SERVICE_STATUS g_serv……
[/Quote]


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);
}

fangchao918628 2010-11-17
  • 打赏
  • 举报
回复
hslinux 2010-11-17
  • 打赏
  • 举报
回复
服务如何实现暂停,继续呢?

程序逻辑上面的东西就该自己控制的了,,,,,


zhanghengsdnu 2010-11-17
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 wjb_yd 的回复:]
哥给你段代码吧。其实MSDN上都有比较详细的解释的。

C/C++ code

wchar_t g_service_name[] = L"SecureProxyServer"; // 服务名称
wchar_t g_service_discription[] = L"安全代理服务器程序"; // 服务描述
SERVICE_STATUS g_service_status;
SERVICE……
[/Quote]

您好,谢谢您了。不过我现在搞不懂的是服务如何实现暂停,继续呢?你这个代码里只是报告下状态就行吗?
wjb_yd 2010-11-12
  • 打赏
  • 举报
回复
哥给你段代码吧。其实MSDN上都有比较详细的解释的。

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);
}


大致的服务就这么写了,具体到你的程序里,略微修改一下就可以了。
zhanghengsdnu 2010-11-11
  • 打赏
  • 举报
回复
能不能在帮帮我啊?
zhanghengsdnu 2010-11-10
  • 打赏
  • 举报
回复
有时候支持也是一种很优秀的帮助,谢谢楼上的。
damingg 2010-11-10
  • 打赏
  • 举报
回复
lz可以搜一下windows服务,windows服务说复杂不复杂,说简单也不简单,但看上2个小时,应该能理解编程模式。照例子做。用服务进程,成像,是否有界面相关?据我所知,服务处理界面好像有点小问题。如果lz遇到了,解决了,还望贴一下!
gules 2010-11-10
  • 打赏
  • 举报
回复
google“windows服务程序”吧。

64,282

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧