How can I run a CLI Application as a Windows Servi

2020-06-17 14:33发布

问题:

Say I have a third party Application that does background work, but prints out all errors and messages to the console. This means, that currently, we have to keep a user logged on to the server, and restart the application (double-click) every time we reboot.

Not so very cool.

I was kind of sure, that there was an easy way to do this - a generic service wrapper, that can be configured with a log file for stdout and stderr.

I did check svchost.exe, but according to this site, its only for DLL stuff. Pity.

EDIT: The application needs to be started from a batch file. FireDaemon seems to do the trick, but I think it is a bit overkill, for something that can be done in <10 lines of python code... Oh well, Not Invented Here...

回答1:

Check out srvany.exe from the Resource Kit. This will let run anything as a service.

You can pass parameters in the service definition to your executable via srvany.exe so you could run a batch file as a service by seting the registry as follows:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService\Parameters]
"Application"="C:\\Windows\\System32\\cmd.exe"
"AppParameters"="/C C:\\My\\Batch\\Script.cmd"
"AppDirectory"="C:\\My\\Batch"

Note: if you set up these keys in RegEdit rather than using a file you only need single backslashes in the values.



回答2:

I'd recommend NSSM: The Non-Sucking Service Manager.

  • 32/64-bit EXEs
  • Public Domain (!)
  • Properly implements service stop messages, and sends the proper signal to your applications for graceful shutdown.


回答3:

Why not simply implement a very thin service wrapper, here's a quickstart guide for writing a Service in .NET Writing a Useful Windows Service in .NET in Five Minutes

When you got that running you can use the Process class to start the application and configure it so that you can handle stdout/stderr yourself (ProcessStartInfo is your friend).



回答4:

Check out FireDaemon. There is a free version (FireDaemon lite I think) that only allows 1 service installed at a time, but this is a very useful tool for setting up services. It also wraps around batch files correctly, if this is required.



回答5:

I second the firedaemon option. You may also want to set the option to allow the service to interact with the desktop to allow it to display the cli output window. They no longer offer a free version but if you search around the web for firedaemon lite you can find the older free lite version or maybe go the for pay route.