Reputation: 422
I am working on a very confused issue all this afternoon, I want to check the windows service status by QueryServiceStatusEx, but always get 0. MSDN says
"If the function fails, the return value is zero. To get extended error information, call GetLastError."
To get more error information, I call GetLastError, the error code is 1.
ERROR_INVALID_HANDLE : The handle is invalid.
Here is my code, e.g. I check the window service :"Spooler", where is wrong in my code? Why I can't get the service SC_HANDLE by using OpenService()?
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;
}
Upvotes: 0
Views: 1211
Reputation: 409176
Your condition is wrong, you write "hahaha alway is 0"
when QueryServiceStatusEx
returns non-zero.
Either remove the !
operator in the condition, or switch places of the outputs.
Upvotes: 3