嘿,我在 Windows 服务中做一些客户端/服务器的东西。这东西很新。
我遇到的问题是,当我尝试通过服务管理器停止服务时,它崩溃了。我添加了一些 MessageBoxes 代码,以跟踪它们崩溃的位置,我发现当它关闭侦听器套接字时它崩溃了!!!
我尝试将服务作为控制台应用程序运行,并且我自己调用了称为SERVICE__CONTROL__STOP事件的函数,以便我可以轻松地重现错误和调试。但它工作正常。只有当我通过服务管理器停止 Windows 服务时,它才会崩溃
这是一些代码
主要功能
int main(int argc, char* argv[])
{
// Create the service object
CTestService CustomServiceObject;
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
std::cerr << "MFC failed to initialize!" << std::endl;
return 1;
}
// Parse for standard arguments (install, uninstall, version etc.)
if (! CustomServiceObject.ParseStandardArgs(argc, argv))
{
// StartService() calls ::StartServiceCtrlDispatcher()
// with the ServiceMain func and stuff
CustomServiceObject.StartService();
}
// When we get here, the service has been stopped
return CustomServiceObject.m_Status.dwWin32ExitCode;
}
服务处理程序回调函数
// static member function (callback) to handle commands from the
// service control manager
void CNTService::Handler(DWORD dwOpcode)
{
// Get a pointer to the object
CNTService* pService = m_pThis;
pService->DebugMsg("CNTService::Handler(%lu)", dwOpcode);
switch (dwOpcode) {
case SERVICE_CONTROL_STOP: // 1
pService->SetStatus(SERVICE_STOP_PENDING);
pService->OnStop();
// ..
// ..
// other event handling
// ..
// ..
}
OnStop() 函数
void CTestService::OnStop()
{
m_sListener.ShutDown(2);
m_sConnected.ShutDown(2);
MessageBox(NULL, "After Shutdown", NULL, IDOK);
m_sConnected.Close();
MessageBox(NULL, "Closed connected socket", NULL, IDOK);
// crashes here when I try to stop through service manager
// but if I run as console application works fine and terminates successfully
m_sListener.Close();
MessageBox(NULL, "Closed listener socket", NULL, IDOK);
::PostThreadMessage(m_dwThreadID, WM_QUIT, NULL, NULL);
MessageBox(NULL, "After PostThreadMessage", NULL, IDOK);
}
编辑:如果建立连接(客户端连接到服务器)并且客户端关闭连接,然后服务停止,则不会崩溃。仅当套接字正在侦听且未接受任何连接或客户端未关闭连接且服务停止时才会崩溃:)
我想它很清楚!