0
votes

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;

}
1
Your code is incomplete; in particular, it seems to be missing a main() function and at least one #include. Please edit your code so it's a minimal reproducible example of your problem, then we can try to reproduce and solve it. You should also read How to Ask.Toby Speight
As an aside, you are consistently calling GetLastError too late. You need to call it immediately, when it's documented to return a meaningful value. Do not intersperse it with any other code, that can both change and invalidate the return value of GetLastError.IInspectable

1 Answers

3
votes

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.