为什么 OpenService() 在我检查窗口服务状态时不起作用?

why OpenService() doesn't work when I check a window service status?

本文关键字:状态 服务 不起作用 窗口 检查 OpenService 为什么      更新时间:2023-10-16

我今天下午都在处理一个非常困惑的问题,我想通过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;
}

你的条件是错误的,你写"hahaha alway is 0"QueryServiceStatusEx返回零时。

要么移除条件下的!运算符,要么切换输出的位置。