Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows EXE can run as service or application. How can I determine if it is running as a service or not?

I am looking for a Win32 API call to return the runtime context of my process. I want to be able to programmatically test if I am running as a service or am I running as standard application process.

Several ideas come to mind.... Since I always have service DAD.exe who runs SON.exe sometimes as his child and in service context --- and sometimes SON.exe is started not by DAD, and by a user.

SON.EXE would do API whoami() to learn which context he is running in.

Now DAD could create an environment var -- and then SON could test for this var -- and if found he knows he is a son of DAD and thus runnning as a service..... But this is weak...

Another idea would be to look at my SID or token and see if I could make this determination.... Again this looks at best more complex vs. a single API check...

like image 243
kevinwaite Avatar asked Sep 29 '11 20:09

kevinwaite


2 Answers

The simple low-tech solution to this is to register your service to run with command line arguments that identify it as a service.

like image 187
David Heffernan Avatar answered Nov 14 '22 17:11

David Heffernan


Another option is to use the Tool Help library. Using it, you take a snapshot of all the currently running processes and then you can walk through all the processes using the Process32First and Process32Next function. These return a structure (PROCESSENTRY32) that looks like:

typedef struct tagPROCESSENTRY32 {
  DWORD     dwSize;
  DWORD     cntUsage;
  DWORD     th32ProcessID;
  ULONG_PTR th32DefaultHeapID;
  DWORD     th32ModuleID;
  DWORD     cntThreads;
  DWORD     th32ParentProcessID;
  LONG      pcPriClassBase;
  DWORD     dwFlags;
  TCHAR     szExeFile[MAX_PATH];
} PROCESSENTRY32, *PPROCESSENTRY32;

as you walk through all the processes, as soon as you find the one whose th32ProcessID matches the one for SON.exe (see GetCurrentProcessId or GetProcessId ). If the th32ParentProcessID of that structure matches that of DAD.exe, then you know you were launched from DAD.exe.

Edit: Answering your comment, I guess you could go one step further and then see who the parent of DAD.exe is, if it's services.exe, then you're a service.

like image 37
zdan Avatar answered Nov 14 '22 17:11

zdan