守护程序编写问题记录

      从去年年底接手该程序。跨过一个为期11天的春节。到现在该程序总算告一段落了。中间遇到了一些问题。为了从挫折中获取养料,也为了培养起自己记笔记的习惯。特将问题记录下来。而其中记录的所有关于问题的猜想和解决思路,都是从该次项目中提取而来。不能保证思路一定正确。

一、常识问题

       将服务启动类型设置为自动类型时候,应用程序异常退出。系统在隔一段时间后,会将应用程序重启。

二、应用安装完成后,启动服务,报1053错误。

     (1) 编写的程序本身存在错误。

     (2) 服务没有按照规定编写,正确示例核心代码如下所示:

     int _tmain(int argc, _TCHAR* argv[]) {
WindowsService* service = ServiceInitial();
if (service == NULL) {
delete service;
return 0;
}
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = L"AUHelper";
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
// 启动服务的控制分派机线程
StartServiceCtrlDispatcher(ServiceTable);
        return 0;

    }

    WindowsService* ServiceInitial() {
char servicePath[MAX_PATH];
if (GetModuleFileNameA(NULL, servicePath, MAX_PATH) == 0) {
return NULL;
}
service = new WindowsService(SERVER_NAME, servicePath, "");
return service;
   }

  void WINAPI ServiceCtrlHandler(DWORD dwCtrl) {
switch (dwCtrl) {
case SERVICE_CONTROL_STOP:
Logger(101, 5, "SERVICE_CONTROL_STOP");
service->ReportServiceStatus(SERVICE_STOP_PENDING, 0);
SetEvent(ghSvcStopEvent);
break;
default:
break;
}
 }

/// <summary>
/// 服务运行的主要执行代码
/// </summary>
void ApplicationStart() {
if (service) { // 报告运行状态
service->ReportServiceStatus(SERVICE_RUNNING, 0);
}
}

/// <summary>
/// 服务运行的主要执行代码终止执行后的后续处理
/// </summary>
void ApplicationEnd() {
//停止服务程序
if (service) {
ServiceCtrlHandler(SERVICE_CONTROL_STOP);
}
}

void WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) {
servieStutusHandle = RegisterServiceCtrlHandlerA(SERVER_NAME, ServiceCtrlHandler);//注册控制处理
ghSvcStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!servieStutusHandle || ghSvcStopEvent == NULL) {
Logger_error("Register CtrlHandler or CreateEvent error");
CloseHandle(ghSvcStopEvent);
return;
}
SERVICE_STATUS serviceStatus;
serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
serviceStatus.dwServiceSpecificExitCode = 0;
service->BindServiceStatus(serviceStatus, servieStutusHandle);
service->ReportServiceStatus(SERVICE_START_PENDING, 100);
try {
ApplicationStart();
WaitForSingleObject(ghSvcStopEvent, INFINITE);
}
catch (const std::system_error& e) {
Logger_error("Application start error,%s", e.what());
}
service->ReportServiceStatus(SERVICE_STOPPED, 0);
CloseHandle(ghSvcStopEvent);
Logger(101, 5, "service stopped");
if (service != NULL) {
delete service;
}
 }

二、#error No Target Architecture

出现这个情况的问题,目前还不是很明确。不过代码中引入#include<Windows.h>会出现很多问题。一般把#include<Windows.h>放入最前面,可以避免很多问题。

三、程序入口设置错误, 提示: ]<K;祕A5? msvcrtd.lib(crtexew.obj) : error LNK2001: unresolved external symbol _WinMain@16 璞m叽鸡pb  

我的程序中出现这个问题,是因为程序入口参数有问题,入口程序参数改成以下形式,问题就解决了:

 int _tmain(int argc, _TCHAR* argv[]);

四、升级程序流程

(1) 下载、压缩升级文件。

(2) 停止服务

(3) 更新可执行文件

(4) 启动服务



猜你喜欢

转载自blog.csdn.net/n_fly/article/details/79426809