How to run a dll as a service?
Solution 1
There are a few different ways to run a DLL as a service. You can either:
Write your own .exe service and have it load your DLL as needed. This is the recommended approach.
-
Use Microsoft's SVCHOST.EXE to host your DLL. Have your DLL export a
ServiceMain()
function, add aServiceDLL
value to your service's Registry key to point at your DLL, add your service name to a new group in SVCHOST's Registry key, and then setsvchost -k <GroupName>
as the executable for your service. See these articles for more details:Getting Started with SVCHOST.EXE Troubleshooting
Note, however, that MSDN's Service Programs documentation warns against this approach:
A service program created with the type SERVICE_WIN32_SHARE_PROCESS contains code for more than one service, enabling them to share code. An example of a service program that does this is the generic service host process, Svchost.exe, which hosts internal Windows services. Note that Svchost.exe is reserved for use by the operating system and should not be used by non-Windows services. Instead, developers should implement their own service hosting programs.
-
Write your service as a kernel-mode driver that exports a
DriverEntry()
function, and add aServiceDLL
value in your service's Registry key pointing at the DLL file. See this article for more details:Driver Development Part 1: Introduction to Drivers.
I would not recommend this approach, unless you are designing your own hardware.
Solution 2
There's actually no inherent reason why you can't use rundll32.exe
as the host executable, though use of rundll32 isn't recommended. (To expand on that: I gather you're trying to build a DLL service as an academic exercise, which is fine. In production, you should of course use an EXE, as you've already done.)
Your main function should have this signature:
void CALLBACK MyServiceEntry(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow)
and should call StartServiceCtrlDispatcher
, in the same way as the main()
or WinMain()
function in a conventional service.
You would then install the service to use the following command line:
rundll32 MyService.dll,MyServiceEntry
For an academic exercise, it would also be acceptable to use svchost.exe
as described in Remy's answer, but it is even more important not to use that in a production context: the use of rundll32 by third parties is supported but not recommended; the use of svchost by third parties is explicitly unsupported.
biprinea
Updated on June 04, 2022Comments
-
biprinea almost 2 years
I know how to write a dll and how to write a service and how to run a dll with
rundll32
, but now I want to write a dll that install as a service in windowsI don't know if that's possible or which function in dll should be exported?
How can I install and run a dll as a service?