Windows服务问题(C++,WinAPI)

Dav*_*yan 1 c++ windows service winapi

我有一个Windows服务的问题,我的应用程序注册Windows服务,但当我尝试运行该服务时,我收到以下错误:"错误1053:服务没有及时响应启动或控制请求".以下代码负责注册服务(我从MSDN获得).

SC_HANDLE schSCManager;
SC_HANDLE schService;

path modulePath("some path to executable");

std::string moduleName = narrow(modulePath.native());

if(!GetModuleFileNameA(NULL, &moduleName[0], MAX_PATH))
{
 throw std::runtime_error("Cannot register service, error code: " +    boost::lexical_cast<std::string>(GetLastError()));
}

// Get a handle to the SCM database. 
   schSCManager = OpenSCManager(NULL,                   // local computer
                                NULL,                   // ServicesActive database 
                                SC_MANAGER_ALL_ACCESS); // full access rights 

   if(!schSCManager) 
   {
      throw std::runtime_error("OpenSCManager failed: " + boost::lexical_cast<std::string>(GetLastError()));
   }

   // Create the service
   schService = CreateServiceA( 
        schSCManager,              // SCM database 
        "name",                  // name of service 
        "displayname",                  // 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 
        narrow(modulePath.native()).c_str(), // path to service's binary 
        NULL,                      // no load ordering group 
        NULL,                      // no tag identifier 
        NULL,                      // no dependencies 
        NULL,                      // LocalSystem account 
        NULL);                     // no password 

   if(!schService) 
   {
      CloseServiceHandle(schSCManager);

      throw std::runtime_error("CreateService failed: " + boost::lexical_cast<std::string>(GetLastError()));
   }
   else
   {
      //std::cout << "\nService installed successfully\n";
   } 

   CloseServiceHandle(schService); 
   CloseServiceHandle(schSCManager);   
Run Code Online (Sandbox Code Playgroud)

你能帮忙解决这个问题吗?

xmo*_*oex 6

如果给定的代码是您尝试过的唯一的东西,那么您就缺少对Windows服务的一些重要要求.请查看文档

您至少需要一个服务主函数(与main方法不同!)和控制处理函数,因为如果没有注册控制处理函数,则无法处理"start"命令(在服务主体中完成)

为了正常工作,您需要:

  1. 普通的主要方法,或以确定是否要安装该服务,否则启动的服务的服务控制调度SERVICE_TABLE_ENTRY
    此表baiscally包含进程名和函数指针到它的服务的主要功能
  2. 您需要服务主函数来注册函数服务控制处理函数,然后启动服务代码函数
  3. 服务代码功能包含与服务工作的代码,它的服务的心脏
  4. 你需要服务控制手柄功能.每当控制代码发送到服务时,都会从Windows的服务控制管理器调用它...这是接收"停止"命令的方法...如果此功能不存在或未正确注册你最终会得到一个像上面提到的错误......