How do we tell if a C++ application is launched as a Windows service?

前端 未结 5 1427
我寻月下人不归
我寻月下人不归 2020-12-16 04:55

We have a console app which we launch from command prompt for debugging, but we also launch this as an NT service for production.

Right now, the code has this logic:<

5条回答
  •  抹茶落季
    2020-12-16 05:17

    Here's some code I created (seems to work nicely). Apologies for missing headers, #defines, etc. If you want to see the full version, look here.

    bool
    CArchMiscWindows::wasLaunchedAsService() 
    {
        CString name;
        if (!getParentProcessName(name)) {
            LOG((CLOG_ERR "cannot determine if process was launched as service"));
            return false;
        }
    
        return (name == SERVICE_LAUNCHER);
    }
    
    bool
    CArchMiscWindows::getParentProcessName(CString &name) 
    {   
        PROCESSENTRY32 parentEntry;
        if (!getParentProcessEntry(parentEntry)){
            LOG((CLOG_ERR "could not get entry for parent process"));
            return false;
        }
    
        name = parentEntry.szExeFile;
        return true;
    }
    
    BOOL WINAPI 
    CArchMiscWindows::getSelfProcessEntry(PROCESSENTRY32& entry)
    {
        // get entry from current PID
        return getProcessEntry(entry, GetCurrentProcessId());
    }
    
    BOOL WINAPI 
    CArchMiscWindows::getParentProcessEntry(PROCESSENTRY32& entry)
    {
        // get the current process, so we can get parent PID
        PROCESSENTRY32 selfEntry;
        if (!getSelfProcessEntry(selfEntry)) {
            return FALSE;
        }
    
        // get entry from parent PID
        return getProcessEntry(entry, selfEntry.th32ParentProcessID);
    }
    
    BOOL WINAPI 
    CArchMiscWindows::getProcessEntry(PROCESSENTRY32& entry, DWORD processID)
    {
        // first we need to take a snapshot of the running processes
        HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if (snapshot == INVALID_HANDLE_VALUE) {
            LOG((CLOG_ERR "could not get process snapshot (error: %i)", 
                GetLastError()));
            return FALSE;
        }
    
        entry.dwSize = sizeof(PROCESSENTRY32);
    
        // get the first process, and if we can't do that then it's 
        // unlikely we can go any further
        BOOL gotEntry = Process32First(snapshot, &entry);
        if (!gotEntry) {
            LOG((CLOG_ERR "could not get first process entry (error: %i)", 
                GetLastError()));
            return FALSE;
        }
    
        while(gotEntry) {
    
            if (entry.th32ProcessID == processID) {
                // found current process
                return TRUE;
            }
    
            // now move on to the next entry (when we reach end, loop will stop)
            gotEntry = Process32Next(snapshot, &entry);
        }
    
    return FALSE;
    

    }

提交回复
热议问题