Windows服务作为控制台应用程序运行,但作为服务自动关闭

时间:2017-09-06 11:56:48

标签: c windows windows-services

所以我创建了一个Windows服务,它在Windows 10中作为服务工作,在Windows 7上作为控制台应用程序工作,但当在Windows 7中作为服务运行时,它会自动停止。

我已按照此处的教程DevX windows service steps

该服务与我的驱动程序通信,并通过执行cmd wmic diskdrive get pnpdeviceid为特定设备提供序列号。

最后这里是main函数和serviceMain函数

 VOID
 WINAPI ServiceMain(
     DWORD argc,
     LPTSTR *argv
 )
 /*
  Description:
    Service Entry Point of the service.
 */
 {
statusHandle = RegisterServiceCtrlHandler(SERVICE_NAME,  ServiceCtrlHandler);

if (statusHandle == NULL)
    return;

// Tell the service controller we are starting
RtlZeroMemory(&serviceStatus, sizeof(serviceStatus));
serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
serviceStatus.dwControlsAccepted = 0;
serviceStatus.dwCurrentState = SERVICE_START_PENDING;
serviceStatus.dwWin32ExitCode = 0;
serviceStatus.dwServiceSpecificExitCode = 0;
serviceStatus.dwCheckPoint = 0;

HRESULT result = ConnectToPort(&port);

serviceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(statusHandle, &serviceStatus);

while (serviceStatus.dwCurrentState == SERVICE_RUNNING) {
    result = GetInformationAndSendSerialNumber(&port);
    if(SUCCEEDED(result)) Sleep(5000);
}

serviceStatus.dwControlsAccepted = 0;
serviceStatus.dwCurrentState = SERVICE_STOPPED;
serviceStatus.dwWin32ExitCode = 0;
serviceStatus.dwCheckPoint = 3;
SetServiceStatus(statusHandle, &serviceStatus);
}

INT 
main(
INT argc,
PCHAR *argv
)
{
SERVICE_TABLE_ENTRY serviceTableEntry[] = 
{
    { SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain},
    {NULL, NULL}
};
StartServiceCtrlDispatcher(serviceTableEntry);
return 0;
}

`

这是我安装服务的方式

sc create Test binpath= C:\Test.exe sc config Test start= auto

1 个答案:

答案 0 :(得分:0)

好吧,我明白了,这是一堆错误。

我已经为FltSendMessage设置了太长时间(100秒)的计时器,我没有初始化FilterGetMessage中的OVERLAPPED结构,这意味着服务进入等待状态直到驱动程序的任何输入。

现在全部整理好了。感谢您的帮助。

编辑: 我也搞砸了断开服务的字符串匹配