在Windows上创建服务

时间:2009-01-31 07:48:40

标签: c++ windows-services

我无法在电脑上启动服务。我的代码基于这篇文章http://www.gamedev.net/reference/articles/article1899.asp

当我从我的int main(int argc,char * argv [])调用installService时,它已成功注册(我可以在msconfig和services.msc中看到它)。但它尚未开始。我通过services.msv手动启动服务,我收到错误“错误2:系统找不到指定的文件”。为什么是这样?我在不久前注册了这些服务,我的外部高清仍处于打开状态(目前已经存储了。我会将一个nondev版本移动到c:/当它准备就绪时)我做错了什么,是否有另一个教程我可以看看(我只找到通过谷歌链接的那个)

#define srvName "MyTestService_01312009"

void installService(char*path)
{
    SC_HANDLE handle = ::OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );
    SC_HANDLE service = ::CreateService(
        handle,
        srvName,
        "MyTestService_01312009b",
        GENERIC_READ | GENERIC_EXECUTE,
        SERVICE_WIN32_OWN_PROCESS,
        SERVICE_AUTO_START,
        SERVICE_ERROR_IGNORE,
        path,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL
    );
}
void uninstallService()
{
    SC_HANDLE handle = ::OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );//?
    SC_HANDLE service = ::OpenService( handle, srvName, DELETE );
    if( service != NULL )
    {
        // remove the service!
        ::DeleteService( service );
    }
}

SERVICE_STATUS_HANDLE hStatus;
SERVICE_STATUS status;

/*
if( ::StartServiceCtrlDispatcher( dispatchTable ) == 0 )
{
    // if this fails, it's probably because someone started us from
    // the command line.  Print a message telling them the "usage"
}
*/
void WINAPI ServiceCtrlHandler( DWORD control )
{
    switch( control )
    {
    case SERVICE_CONTROL_SHUTDOWN:
    case SERVICE_CONTROL_STOP:
        // do shutdown stuff here

        status.dwCurrentState = SERVICE_STOPPED;
        status.dwWin32ExitCode = 0;
        status.dwCheckPoint = 0;
        status.dwWaitHint = 0;
        break;
    case SERVICE_CONTROL_INTERROGATE:
        // just set the current state to whatever it is...
        break;
    }

    ::SetServiceStatus( hStatus, &status );
}
void WINAPI ServiceDispatch( DWORD numArgs, char **args )
{
    // we have to initialize the service-specific stuff
    memset( &status, 0, sizeof(SERVICE_STATUS) );
    status.dwServiceType = SERVICE_WIN32;
    status.dwCurrentState = SERVICE_START_PENDING;
    status.dwControlsAccepted = SERVICE_ACCEPT_STOP;

    hStatus = ::RegisterServiceCtrlHandler( srvName, &ServiceCtrlHandler );

    // more initialization stuff here
    FILE *f = fopen("c:/testSrv.bin", "wb");
    ::SetServiceStatus( hStatus, &status );
}
SERVICE_TABLE_ENTRY dispatchTable[] =
{
    { srvName, &ServiceDispatch },
    { NULL, NULL }
};

1 个答案:

答案 0 :(得分:1)

也许您可以使用Process Monitor找出错误。

启动它,查找与服务启动相关的NAME NOT FOUND结果。