473,789 Members | 2,876 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to detect if the current process (or dll) run as service ???

Hi.

I am working on a managed dll.
What code can I use in C# to detect if my dll is running under a
service (like IIS) or called from a 'normal' program.

Thanks

Thierry
Jul 21 '05 #1
3 6880
Check the value of the System.Environm ent.UserName property. If it is a
non-user account, such as "SYSTEM" or "Network", then it is safe to assume
that the process is running as a service.

Good luck,
Derek Stone
EliteVB.com

"Thierry" <no**@none.co m> wrote in message
news:e5******** ******@TK2MSFTN GP09.phx.gbl...
Hi.

I am working on a managed dll.
What code can I use in C# to detect if my dll is running under a
service (like IIS) or called from a 'normal' program.

Thanks

Thierry

Jul 21 '05 #2
That is not necessarily correct because the user could change the identity
that the service is running under.

The problem is that a service is nothing more than an executable. Here are
a couple things that you might try. I have not actually done these but they
make logical sense if you can get them to work.

1) All services inherit from ServiceBase. You might check the call stack
to see if the very first method called belonged to a class that inherited
from ServiceBase.
2) Or you could use the ServiceControll er to get the names of all services
registered in the system and compare them with your application. If there
is a match, you may be running in a service. This is not perfect I guess
since it might be possible to have a service and a regular application with
the same name.

"Derek Stone" <ds****@elitevb .com> wrote in message
news:#$******** ******@TK2MSFTN GP11.phx.gbl...
Check the value of the System.Environm ent.UserName property. If it is a
non-user account, such as "SYSTEM" or "Network", then it is safe to assume
that the process is running as a service.

Good luck,
Derek Stone
EliteVB.com

"Thierry" <no**@none.co m> wrote in message
news:e5******** ******@TK2MSFTN GP09.phx.gbl...
Hi.

I am working on a managed dll.
What code can I use in C# to detect if my dll is running under a
service (like IIS) or called from a 'normal' program.

Thanks

Thierry


Jul 21 '05 #3
antichrist
1 New Member
Expand|Select|Wrap|Line Numbers
  1. [DllImport("advapi32.dll", CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
  2. private extern static IntPtr OpenSCManager(string machineName, string databaseName, int access);        
  3.  
  4. [DllImport("advapi32.dll",SetLastError=true, CharSet=CharSet.Auto)]
  5. private static extern bool EnumServicesStatusEx(IntPtr hSCManager,
  6.     int InfoLevel, int dwServiceType,
  7.     int dwServiceState, IntPtr lpServices, UInt32 cbBufSize,
  8.     out uint pcbBytesNeeded, out uint lpServicesReturned,
  9.     ref uint lpResumeHandle, string pszGroupName);
  10.  
  11. [DllImport("advapi32.dll")]
  12. private static extern bool CloseServiceHandle(IntPtr hSCObject);
  13.  
  14. [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
  15. private static extern int GetCurrentProcessId();                    
  16.  
  17. [StructLayout(LayoutKind.Sequential, Pack=1)]
  18. public struct ENUM_SERVICE_STATUS_PROCESS
  19. {
  20.     public static readonly int SizeOf = Marshal.SizeOf(typeof(ENUM_SERVICE_STATUS_PROCESS));
  21.  
  22.     [MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
  23.     public string pServiceName;
  24.  
  25.     [MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
  26.     public string pDisplayName;
  27.  
  28.     public SERVICE_STATUS_PROCESS ServiceStatus;
  29. }
  30.  
  31. [StructLayout(LayoutKind.Sequential, Pack=1)]
  32. public struct SERVICE_STATUS_PROCESS
  33. {
  34.     public static readonly int SizeOf = Marshal.SizeOf(typeof(SERVICE_STATUS_PROCESS));
  35.  
  36.     public int dwServiceType;  
  37.     public int dwCurrentState;  
  38.     public int dwControlsAccepted;  
  39.     public int dwWin32ExitCode;  
  40.     public int dwServiceSpecificExitCode;  
  41.     public int dwCheckPoint;  
  42.     public int dwWaitHint;  
  43.     public int dwProcessId;  
  44.     public int dwServiceFlags;
  45.  
  46. // http://www.hoytsoft.org/sourceFile.aspx?zip=files/HoytSoft.ServiceProcess_src(Rev3).zip&source=Service%20Base/ServicesAPI.cs
  47. private const int SERVICE_NO_CHANGE = -1;
  48. private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
  49. private const int SC_ENUM_PROCESS_INFO = 0;
  50.  
  51. private enum ServiceType { SERVICE_KERNEL_DRIVER = 0x1, SERVICE_FILE_SYSTEM_DRIVER = 0x2, SERVICE_WIN32_OWN_PROCESS = 0x10, SERVICE_WIN32_SHARE_PROCESS = 0x20, SERVICE_INTERACTIVE_PROCESS = 0x100, SERVICETYPE_NO_CHANGE = SERVICE_NO_CHANGE, SERVICE_WIN32 = (SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS) }
  52. private enum ServiceStartType { SERVICE_BOOT_START = 0x0, SERVICE_SYSTEM_START = 0x1, SERVICE_AUTO_START = 0x2, SERVICE_DEMAND_START = 0x3, SERVICE_DISABLED = 0x4, SERVICESTARTTYPE_NO_CHANGE = SERVICE_NO_CHANGE }
  53. private enum ServiceErrorControl { SERVICE_ERROR_IGNORE = 0x0, SERVICE_ERROR_NORMAL = 0x1, SERVICE_ERROR_SEVERE = 0x2, SERVICE_ERROR_CRITICAL = 0x3, msidbServiceInstallErrorControlVital = 0x8000, SERVICEERRORCONTROL_NO_CHANGE = SERVICE_NO_CHANGE }
  54. private enum ServiceStateRequest { SERVICE_ACTIVE = 0x1, SERVICE_INACTIVE = 0x2, SERVICE_STATE_ALL = (SERVICE_ACTIVE | SERVICE_INACTIVE) }
  55. private enum ServiceControlType { SERVICE_CONTROL_STOP = 0x1, SERVICE_CONTROL_PAUSE = 0x2, SERVICE_CONTROL_CONTINUE = 0x3, SERVICE_CONTROL_INTERROGATE = 0x4, SERVICE_CONTROL_SHUTDOWN = 0x5, SERVICE_CONTROL_PARAMCHANGE = 0x6, SERVICE_CONTROL_NETBINDADD = 0x7, SERVICE_CONTROL_NETBINDREMOVE = 0x8, SERVICE_CONTROL_NETBINDENABLE = 0x9, SERVICE_CONTROL_NETBINDDISABLE = 0xA, SERVICE_CONTROL_DEVICEEVENT = 0xB, SERVICE_CONTROL_HARDWAREPROFILECHANGE = 0xC, SERVICE_CONTROL_POWEREVENT = 0xD, SERVICE_CONTROL_SESSIONCHANGE = 0xE,  }
  56. private enum ServiceState { SERVICE_STOPPED = 0x1, SERVICE_START_PENDING = 0x2, SERVICE_STOP_PENDING = 0x3, SERVICE_RUNNING = 0x4, SERVICE_CONTINUE_PENDING = 0x5, SERVICE_PAUSE_PENDING = 0x6, SERVICE_PAUSED = 0x7  }
  57. private enum ServiceControlAccepted { SERVICE_ACCEPT_STOP = 0x1, SERVICE_ACCEPT_PAUSE_CONTINUE = 0x2, SERVICE_ACCEPT_SHUTDOWN = 0x4, SERVICE_ACCEPT_PARAMCHANGE = 0x8, SERVICE_ACCEPT_NETBINDCHANGE = 0x10, SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x20, SERVICE_ACCEPT_POWEREVENT = 0x40, SERVICE_ACCEPT_SESSIONCHANGE = 0x80 }
  58. private enum ServiceControlManagerType { SC_MANAGER_CONNECT = 0x1, SC_MANAGER_CREATE_SERVICE = 0x2, SC_MANAGER_ENUMERATE_SERVICE = 0x4, SC_MANAGER_LOCK = 0x8, SC_MANAGER_QUERY_LOCK_STATUS = 0x10, SC_MANAGER_MODIFY_BOOT_CONFIG = 0x20, SC_MANAGER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_LOCK | SC_MANAGER_QUERY_LOCK_STATUS | SC_MANAGER_MODIFY_BOOT_CONFIG }
  59. private enum ACCESS_TYPE { SERVICE_QUERY_CONFIG = 0x1, SERVICE_CHANGE_CONFIG = 0x2, SERVICE_QUERY_STATUS = 0x4, SERVICE_ENUMERATE_DEPENDENTS = 0x8, SERVICE_START = 0x10, SERVICE_STOP = 0x20, SERVICE_PAUSE_CONTINUE = 0x40, SERVICE_INTERROGATE = 0x80, SERVICE_USER_DEFINED_CONTROL = 0x100, SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL }
  60.  
  61. public static bool IsCurrentProcessAService()
  62. {
  63.     return IsProcessAService(GetCurrentProcessId());
  64. }
  65.  
  66. //public static bool IsProcessAService(int processId)
  67. public static bool IsProcessAService(int processId)
  68. {
  69.     IntPtr handle = IntPtr.Zero;
  70.     IntPtr buf = IntPtr.Zero;
  71.     try
  72.     {
  73.         handle = OpenSCManager(null, null, (int)ServiceControlManagerType.SC_MANAGER_ALL_ACCESS);
  74.         if(handle != IntPtr.Zero)
  75.         {
  76.             uint iBytesNeeded = 0;
  77.             uint iServicesReturned = 0;
  78.             uint iResumeHandle = 0;
  79.  
  80.             ENUM_SERVICE_STATUS_PROCESS infoLevel = new ENUM_SERVICE_STATUS_PROCESS();
  81.             if(!EnumServicesStatusEx(handle, SC_ENUM_PROCESS_INFO, (int)ServiceType.SERVICE_WIN32, (int)ServiceStateRequest.SERVICE_STATE_ALL, IntPtr.Zero, 0, out iBytesNeeded, out iServicesReturned, ref iResumeHandle, null))
  82.             {
  83.                 buf = Marshal.AllocHGlobal((int)iBytesNeeded);
  84.                 if(!EnumServicesStatusEx(handle, SC_ENUM_PROCESS_INFO, (int)ServiceType.SERVICE_WIN32, (int)ServiceStateRequest.SERVICE_STATE_ALL, buf, iBytesNeeded, out iBytesNeeded, out iServicesReturned, ref iResumeHandle, null))
  85.                     throw new Win32Exception(Marshal.GetLastWin32Error());
  86.  
  87.                 ENUM_SERVICE_STATUS_PROCESS serviceStatus;
  88.                 int iPtr = buf.ToInt32();
  89.                 for(int i = 0; i < (int)iServicesReturned; i++)
  90.                 {
  91.                     serviceStatus = (ENUM_SERVICE_STATUS_PROCESS)Marshal.PtrToStructure(new IntPtr(iPtr), typeof(ENUM_SERVICE_STATUS_PROCESS));
  92.  
  93.                     //System.Console.WriteLine("{0} - {1}", serviceStatus.pServiceName, serviceStatus.ServiceStatus.dwProcessId);
  94.  
  95.                     if(serviceStatus.ServiceStatus.dwProcessId == processId)
  96.                         return true;
  97.  
  98.                     iPtr += ENUM_SERVICE_STATUS_PROCESS.SizeOf;
  99.                 }                        
  100.             }
  101.         }
  102.  
  103.         return false;
  104.     }
  105.     finally
  106.     {
  107.         if(handle != IntPtr.Zero)
  108.             CloseServiceHandle(handle);
  109.  
  110.         if(buf != IntPtr.Zero)
  111.             Marshal.FreeHGlobal(buf);
  112.     }
  113. }
  114.  
Jul 4 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2510
by: Max Berghammer | last post by:
Hi ! Is there any way to redirect the standard-outputstream or standard-errorstream of the currently running process ? I know that i can spawn a new process and redirect its standard-outputstream or standard-errorstream, but i need access to the streams of the CURRENT process as this one interops with a selfmade COM-Server, that uses an old third-party (compiled!!!) library, that is printing (Error)Messages to stderr/stdout. Is this...
3
22612
by: Regis Melo | last post by:
Hello, I'm trying to get the "EXE" name of app that runs the current window. To get the current window I use: private static extern int GetForegroundWindow();
0
1073
by: Jean-Pierre Fouche | last post by:
I have a server app which hosts a remote object, published via http. The app works fine as a self-standing .exe. However, when I host the same code as a library .dll, the object is unavailable to clients. I can verify that the object is indeed published on http://localhost:8080/object1uri by viewing the location in my browser. However, the client reports an error : Requested service not found (Remoting Exception)
2
337
by: Thierry | last post by:
Hi. I am working on a managed dll. What code can I use in C# to detect if my dll is running under a service (like IIS) or called from a 'normal' program. Thanks Thierry
2
13567
by: Sharon | last post by:
How do I find the full path where my current process is executed from? System.Environment.CurrentDirectory and System.IO.Directory.GetCurrentDirectory is not good enough because they may be changed any many circumstance and not reflect the original location the current process is started from. Any Idea? ----------
2
2379
by: Maciej Bliziñski | last post by:
Hello Pythonists, I'd like to write for myself a tiny program that counts time spent on each virtual desktop (in GNOME). In order to do that, I need my program to detect the current virtual desktop. I've googled for it for about one hour and couldn't find any solution. The closest thing I found is set of tutorials: http://www.pygtk.org/articles.html Unfortunately, none of them answers my questions: How to detect current virtual...
5
1802
by: wheels619 | last post by:
Hi, I need the directory of a running process or service's executable. Any ideas how to do this? I looked up some Win APIs but none to accomplish this task. I noticed there is a .StartInfo.WorkingDirectory in the process object but it is always empty. I would think that the working dir would be the same as the EXE if not defined.
1
2209
by: Maxwell2006 | last post by:
Hi, How can I get a list of AppDomains under the current process? Thank you,
0
8730
by: PRR | last post by:
Here is a code i found on "how to enumerate appdomains in a current process". The original code was posted by Thomas Scheidegger Add the following as a COM reference - ~\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscoree.tlb using mscoree; using System.Runtime.InteropServices;
0
9665
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9511
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10408
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10199
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9020
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7529
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3697
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.