gpt4 book ai didi

c++ - 是否每个 Windows 服务都调用其可执行的 main 函数?

转载 作者:可可西里 更新时间:2023-11-01 11:15:30 26 4
gpt4 key购买 nike

我有一个关于 Windows 服务的非常基本的问题,我有这个安装的 main 函数,我可以用它来安装我的服务,还有一些配置数据加载到 main 函数中:

int 
wmain(int argc, WCHAR* argv[])
{
// it reads config and fill a global struct.
ReadConfig();

// if command == 'install'
install_service();
}

这是服务的主要功能:

void WINAPI ServiceMain(DWORD argc, WCHAR* argv[])
{
// this method retrieves the global config object.
auto config_data = GetConfigData();

// service stuff
}

这是在我的 wmain 函数中调用的另一个函数,如果它在没有任何参数的情况下运行 (argc = 0 !):

bool
ServiceRunAsService()
{
static const SERVICE_TABLE_ENTRY table[] = {
{ SERVICE_NAME, ServiceMain },
{ NULL, NULL }
};

g_hStopService = CreateEvent(0, TRUE, FALSE, 0);
return StartServiceCtrlDispatcher(table) && GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT;
}

我的问题是,当 Windows 想要运行我的服务时(在 PC 关闭并再次打开之后),它是否调用了我的 wmain 函数(因此调用了 ReadConfig 函数)还是调用注册的ServiceMain 函数?我想指出 install_service 方法,通过 GetModuleFileName 找到可执行文件的路径并将其传递给 CreateServiceScmManager

最佳答案

当可执行文件启动时,无论出于何种原因,都会调用 exe 入口点(如果进程之前没有崩溃或 Hook )。所以在你的情况下总是调用你的wmainwmainCRTStartup(或者你的exe真正入口点的名称是什么)。所以是的 - 每次可执行文件启动时都会调用您的 wamin

而且系统根本无法调用ServiceMain。它根本不知道它的地址。它没有注册。当您注册 exe 服务时,您注册了服务的命令行,但没有在 exe 中注册任何导出的名称。您的可执行文件成为服务并仅在 StartServiceCtrlDispatcher 之后注册 ServiceMain,它必须从您的 wmain

调用

即使 dll 形式的服务与 svchost.exe 一起工作 - 您注册导出的函数,它必须从您的 dll 调用作为服务入口点,或者默认情况下 ServiceMain .但无论如何,即使在这种情况下,首先你的 DllMain (dll 入口点)将被调用(如果存在)。如果是 exe - 入口点是强制性的并且总是会被调用

关于c++ - 是否每个 Windows 服务都调用其可执行的 main 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53462047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com