我创建了一个 Http 服务器(C++ Win 32 控制台应用程序),我想运行它是服务。 该服务器有主线程和监听器线程,它们将监听传入的流量。主线程将永远阻塞。
我创建了一个使用 SimpleSC 的 NSIS 安装程序安装和运行服务器的插件
SimpleSC::InstallService "HttpServer" "HttpServer" "16" "2" "$INSTDIR\Server.exe" "" "" ""
SimpleSC::StartService "HttpServer" "" 30
我可以安装服务但它没有启动并返回 1053 错误。这是因为主线程阻塞吗?请帮我解决这个问题。
最佳答案
问题一定出在您的服务代码中。在调用 RegisterServiceCtrlHandler()
时声明的服务控制处理程序中,您需要处理多种请求类型并根据反馈返回系统服务管理器。它让系统知道您的服务工作正常以及它的当前状态。
如果您没有回答所有请求类型(尤其是SERVICE_CONTROL_INTERROGATE
),或者如果您没有在限定时间内回答,系统将推断您的服务失败/停止。
这是我在我的代码中使用的控制处理程序示例:
//Feedback() is a custom function to put log into the system events and / or OutputDebugString()
//mSrvStatus is a global SERVICE_STATUS
void WINAPI SrvControlHandler(DWORD Opcode) {
DWORD state;
switch (Opcode) {
case SERVICE_CONTROL_PAUSE:
Feedback(FEED_EVENTS|FEED_ODS, "Pausing %s", SRVNAME);
bActive = false;
state = SERVICE_PAUSED;
break;
case SERVICE_CONTROL_CONTINUE:
//refresh our settings from registry before continuing
GetRegistrySettings();
Feedback(FEED_EVENTS|FEED_ODS, "Continuing %s with refresh=%d", SRVNAME, dwRefresh);
bActive = true;
state = SERVICE_RUNNING;
break;
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
Feedback(FEED_EVENTS|FEED_ODS, "Stopping %s", SRVNAME);
ReportSrvStatus(SERVICE_STOP_PENDING, NO_ERROR, 0); //ok, we begin to stop
//The final ReportSrvStatus(SERVICE_STOPPED, NO_ERROR, 0);
//is sent from the function that started the service
//that is waiting forever on the hSrvStopEvt event
bActive = false; //we tell the thread to stop fetching
SetEvent(hSrvStopEvt); //and we signal the final event
return;
break;
case SERVICE_CONTROL_INTERROGATE:
state = mSrvStatus.dwCurrentState;
Feedback(FEED_ODS, "%s interrogated by SCM, returned %d", SRVNAME, state);
break;
default:
Feedback(FEED_ODS, "other control resquest ?? - %d", Opcode);
state = mSrvStatus.dwCurrentState;
}
ReportSrvStatus(state, NO_ERROR, 0);
}
/* Sets the current service status and reports it to the SCM.
Parameters:
dwCurrentState - The current state (see SERVICE_STATUS)
dwWin32ExitCode - The system error code
dwWaitHint - Estimated time for pending operation, in milliseconds
*/
void ReportSrvStatus( DWORD dwCurrentState,
DWORD dwWin32ExitCode,
DWORD dwWaitHint) {
static DWORD dwCheckPoint = 1;
mSrvStatus.dwCurrentState = dwCurrentState;
mSrvStatus.dwWin32ExitCode = dwWin32ExitCode;
mSrvStatus.dwWaitHint = dwWaitHint;
if (dwCurrentState == SERVICE_START_PENDING)
mSrvStatus.dwControlsAccepted = 0;
else mSrvStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_PAUSE_CONTINUE|SERVICE_ACCEPT_SHUTDOWN;
if ( (dwCurrentState == SERVICE_RUNNING) ||
(dwCurrentState == SERVICE_STOPPED) )
mSrvStatus.dwCheckPoint = 0;
else mSrvStatus.dwCheckPoint = dwCheckPoint++;
SetServiceStatus( hSrvStatus, &mSrvStatus );
}
关于c++ - Windows服务安装返回错误1053,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20397620/