C++ 以服务形式加载驱动的问题!急切!!!
代码核心如下:BOOL LoadDriver( IN LPCTSTR lpFileName )
{
HANDLE hDevice=0;
SC_HANDLE hSCManager = OpenSCManager( NULL, NULL,SC_MANAGER_CREATE_SERVICE );
if ( NULL != hSCManager )
{
SC_HANDLE hService = CreateService( hSCManager, SERVICE_NAME,
SERVICE_NAME, SERVICE_START,
SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START,
SERVICE_ERROR_IGNORE, lpFileName, NULL, NULL, NULL, NULL, NULL );
if ( ERROR_SERVICE_EXISTS == GetLastError() )
{
hService = OpenService( hSCManager, SERVICE_NAME, SERVICE_START );
}
if(!StartService( hService, 0, NULL ))
{
cout<<"StartService Error!\n";
return false;
}
CloseServiceHandle( hService );
CloseServiceHandle( hSCManager );
hDevice = CreateFileA( DEVICE_NAME,GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
}
if(hDevice)
{
cout<<"hDevice return true!\n";
return true;
}
else
{
cout<<"Error: hDevice->false !\n";
return false;
}
}
BOOL UnloadDriver()
{
SC_HANDLE hSCManager = OpenSCManager( NULL, NULL,SC_MANAGER_CREATE_SERVICE );
if ( NULL != hSCManager )
{
SC_HANDLE hService = OpenService( hSCManager, SERVICE_NAME, DELETE | SERVICE_STOP );
if ( NULL != hService )
{
SERVICE_STATUS ss;
if(!ControlService( hService, SERVICE_CONTROL_STOP, &ss ))
cout<<"ControlService - >失败!\n";
else
cout<<"ControlService ->成功!\n";
CloseServiceHandle( hService );
}
else
return false;
CloseServiceHandle( hSCManager );
}
else
return false;
return true;
}
——————————————————————————————————
问题如下,程序开始运行,LoadDriver() -> 成功,然后UnloadDriver() -> 成功; 看似没问题了,但如果再LoadDriver(), 却失败!! 因为StartService()失败了!!! ::如果关闭程序,再重新运行,LoadDriver() 又是成功的~~~~。 我不知道原因,也就不知道如何去解决了,请高人指点一下。
我的目标就是需要程序运行的时候反复地执行如下步骤都能成功:
LoadDriver()->UnloadDriver()->LoadDriver()->UnloadDriver()->LoadDriver()->UnloadDriver()->..............................
请高人指点一下。