|
阅读:1686回复:3
关于驱动启动的问题
前段时间买了《从汇编语言到WINDOWS内核编程》这本书,看了大部分了,一直有个问题想问下,一个编译好的sys文件,如何用自己的程序装载起来。查了资料可以用 OpenSCManager,CreateService, StartService,这3个函数启动驱动,但是自己一直没实现,希望老鸟给点提示。。。
|
|
|
沙发#
发布于:2009-10-19 09:13
bool LoadDriver(LPCTSTR lpszDriverName, LPCTSTR lpszDriverPath)
{
char szDriverFilePath[MAX_PATH];
GetFullPathName(lpszDriverPath, MAX_PATH, szDriverFilePath, NULL);
bool bRet = true;
DWORD dwReturn;
SC_HANDLE hServiceMgr = NULL;
SC_HANDLE hServiceSys = NULL;
// 打开服务管理器
hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (!hServiceMgr)
{
printf("OpenSCManager() Error!\n");
bRet = false;
goto END;
}
// 创建驱动服务
hServiceSys = CreateService(hServiceMgr,
lpszDriverName, // 驱动服务名
lpszDriverName, // 驱动服务显示名
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER, // 内核驱动
SERVICE_DEMAND_START, // 手动启动
SERVICE_ERROR_IGNORE, // 忽略错误
szDriverFilePath, // 服务文件路径
NULL,
NULL,
NULL,
NULL,
NULL);
if (!hServiceSys)
{
dwReturn = GetLastError();
if ((dwReturn != ERROR_IO_PENDING) && (dwReturn != ERROR_SERVICE_EXISTS))
{
// 服务创建失败,未知错误
printf("CreateService() Error : %d!\n", dwReturn);
bRet = false;
goto END;
}
// 服务已经存在,只需打开
hServiceSys = OpenService(hServiceMgr, lpszDriverName, SERVICE_ALL_ACCESS);
if (!hServiceSys)
{
printf("OpenService() Error!\n");
bRet = false;
goto END;
}
}
// 启动服务
bRet = StartService(hServiceSys, NULL, NULL);
if (!bRet)
{
dwReturn = GetLastError();
if ((dwReturn != ERROR_IO_PENDING) && (dwReturn != ERROR_SERVICE_ALREADY_RUNNING))
{
printf("StartService() Error! : %d\n", dwReturn);
bRet = false;
goto END;
}
else
{
if (dwReturn == ERROR_IO_PENDING)
{
// 设备被挂起
printf("StartService() Error! : ERROR_IO_PENDING\n");
bRet = false;
goto END;
}
else
{
// 设备已经运行
bRet = true;
goto END;
}
}
}
END:
if (hServiceSys)
{
CloseHandle(hServiceSys);
}
if (hServiceMgr)
{
CloseHandle(hServiceMgr);
}
return bRet;
}
bool UnloadDriver(LPCTSTR lpszSvrName)
{
bool bRet = true;
SERVICE_STATUS SrvStatus;
SC_HANDLE hServiceMgr = NULL;
SC_HANDLE hServiceSys = NULL;
// 打开服务管理器
hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (!hServiceMgr)
{
printf("OpenSCManager() Error!\n");
bRet = false;
goto END;
}
// 打开驱动服务
hServiceSys = OpenService(hServiceMgr, lpszSvrName, SERVICE_ALL_ACCESS);
if (!hServiceSys)
{
printf("OpenService() Error!\n");
bRet = false;
goto END;
}
// 停止驱动服务
if (!ControlService(hServiceSys, SERVICE_CONTROL_STOP, &SrvStatus))
{
printf("ControlService() Error!\n");
bRet = false;
}
// 卸载驱动服务
if (!DeleteService(hServiceSys))
{
printf("DeleteService() Error!\n");
bRet = false;
}
END:
if (hServiceSys)
{
CloseHandle(hServiceSys);
}
if (hServiceMgr)
{
CloseHandle(hServiceMgr);
}
return bRet;
} |
|
|
板凳#
发布于:2009-10-20 16:34
实在 太谢谢楼上的人了,
|
|
|
地板#
发布于:2009-11-13 21:37
学习一下
|
|