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 windows
I 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?
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:A description of Svchost.exe
Getting Started with SVCHOST.EXE Troubleshooting
Tricks with SVCHOST.EXE
The Service Host
Note, however, that MSDN's Service Programs documentation warns against this approach:
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.
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:
and should call
StartServiceCtrlDispatcher
, in the same way as themain()
orWinMain()
function in a conventional service.You would then install the service to use the following command line:
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.