开发者

How can I tell if the current process is a service or not (C++, Win32)?

How can I tell if the application my code is running in, is it in a service or an application? Why do I want to know this - I'm writing some code that is injected into the target application and that code has no way of knowing this information up front, so it has to work it out itself.

I cannot rely on any code being called from the service control manager, start, stop, or command line parameters.

I'm currently looking at GetCons开发者_如何转开发oleWindow() which I hope will return NULL for a service (no console) and a window handle for any application (has a console). Not sure how valid this assumption is.

Any ideas for a better solution?


Search the current process id (GetCurrentProcessId) from the list of all running services (EnumServicesStatusEx)?


The assumption of GetConsoleWindow() is not valid.

It seems to me that you care about the context of your process more. Are you asking that if your program is running in service context or the user session? If so, use ProcessIdToSessionId() http://msdn.microsoft.com/en-us/library/aa382990%28v=VS.85%29.aspx to get your session id and you will know it.


Use WMI to query for Win32_Service instances where 'ProcessId=MyProcessid'. If there is no match, then your process is not a service.

Background on WMI app creation in C++ here.


For Windows Vista or later you can check the session id. Session 0 is reserved for services and non-interactive programs. User sessions start from 1.


Use OpenProcessToken to get the current process token. Then use CheckTokenMembership to see if the token includes the WinServiceSid well-known SID.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜