Search code examples
cwindowswindows-servicesmingw

How do I check if my executable is running for a service or for a normal program?


I'm developing a win service in using mingw I've been trying for hours I looked for examples on the internet I used ChatGPT and nothing it returned works and the few examples I found had nothing to do with what I wanted

I hope there is some way to do this the idea and before i create the SERVICE_TABLE_ENTRY i can check if my executable was started for a windows service, if yes i create the SERVICE_TABLE_ENTRY if I don't do anything else.


Solution

  • A little late, but this works for me to distinguish between invocation by services.exe or cmd.exe:

       static BOOL AreWeAService()
        {  BOOL  bIsAService = FALSE;
           BYTE  sidService[SECURITY_MAX_SID_SIZE] = { 0 };
           DWORD cbSidSize = SECURITY_MAX_SID_SIZE;
        
           /* Create a SID for the Windows Service Group (S‒1‒5‒6) and check it against ours */
           if (TRUE == ::CreateWellKnownSid(WinServiceSid, nullptr, &sidService, &cbSidSize))
              ::CheckTokenMembership(NULL, &sidService, &bIsAService);
        
           return bIsAService;
        }
    

    It's important to allocate the SID block as SECURITY_MAX_SID_SIZE or the CheckTokenMembership API call will fail with an "Invalid parameter" error.