我今天下午正在处理一个非常混乱的问题,我想通过QueryServiceStatusEx检查Windows服务状态,但总是得到0. MSDN说
“如果函数失败,返回值为零。要扩展 错误信息,调用GetLastError。“
要获取更多错误信息,我调用GetLastError,错误代码为1。
ERROR_INVALID_HANDLE:句柄无效。
这是我的代码,例如我检查窗口服务:“后台处理程序”,我的代码出错了?为什么我不能通过使用OpenService()来获取服务SC_HANDLE?
bool isServiceStart()
{
SERVICE_STATUS_PROCESS status;
SC_HANDLE schSCManager;
SC_HANDLE schService;
//get hadnle to the scm database
schSCManager = OpenSCManager(
NULL, //local machine
NULL, //services acitive database
SC_MANAGER_ALL_ACCESS
);
if(NULL == schSCManager){
qDebug() << "Open SCManager failed: " << (GetLastError() == ERROR_ACCESS_DENIED);
CloseServiceHandle(schSCManager);
return false;
}
//Get a hadle to the service
QString serviceName = "Spooler";
schService = OpenService(
schSCManager, //database
(LPCTSTR)serviceName.data(),
SERVICE_ALL_ACCESS
);
if(schService == NULL){
qDebug() << "service doesn't exist: " << GetLastError();
CloseServiceHandle(schSCManager);
return false;
}
DWORD dwBytesNeeded;
if(!QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO, // information level
(LPBYTE) &status, // address of structure
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded // size needed if buffer is too small
))
{
qInfo() << "service status" << status.dwCurrentState;
}else{
qInfo() << "hahaha alway is 0" <<GetLastError();
}
return false;
}
答案 0 :(得分:3)
您的情况有误,当"hahaha alway is 0"
返回非 -zero时,您会写QueryServiceStatusEx
。
删除条件中的!
运算符,或者切换输出的位置。