爱编程的欧巴

让我们成长吧~
  博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

使用Windows Service Wrapper快速创建一个Windows Service

前言

今天介绍一个小工具的使用。我们都知道Windows Service是一种特殊的应用程序,它的好处是可以一直在后台运行,相对来说,比较适合一些需要一直运行同时不需要过多用户干预的应用程序,这一类我们称之为“服务”吧

编写Windows Service其实是不难的,尤其是如果有Visual Studio的话。但是仍然是有不少童鞋觉得略显繁琐,同时,如果有一些其他的程序,我们只拿到一个exe,或者一个bat,但又想让他象服务一样运行,怎么办呢

答案就是可以使用如下的一个工具,它的名称就叫:Windows Service Wrapper,简称WSW。

wsw的基本使用

一般的使用步骤是:

1. 下载wsw的最新版本,放在任意的位置,修改成你想要的任何名字

2.编写一个同名的xml文件

3.使用Install命令进行安装

4.如果想要卸载,则使用Uninstall命令

 

 

https://kenai.com/projects/winsw/pages/Home

This project creates a wrapper executable that can be used to host any executable as an Windows service.

Download

The binaries are available here for download.

Usage

During your development...

  1. Take winsw.exe from the distribution, and rename it to your taste (such as myapp.exe)
  2. Write myapp.xml (see Configuration Syntax for more details)
  3. Place those two files side by side when you deploy your application, because that's how winsw.exe discovers its configuration.

At runtime...

  • To install a service, run myapp.exe install
  • To start a service, run myapp.exe start
  • To stop a service, run myapp.exe stop
  • To restart a service, run myapp.exe restart
  • To uninstall a service, run myapp.exe uninstall

When there's a problem, these commands also report an error message to stderr. On a successful completion, these commands do no produce any output and exit with 0.

In addition, you can also run myapp.exe status to have it print out the current status of the service to stdout. Again, any error encountered during the processing would cause output to be reported to stderr.

All these commands use the same set of exit code to indicate its result.

Deferred File Operations

To support self updating services, winsw offers a mechanism to perform file operations before a service start up. This is often necessary because Windows prevents files from overwritten while it's in use.

To perform file operations, write a text file (in the UTF-8 encoding) at myapp.copies (that is, it's in the same directory asmyapp.xml but with a different file extension), and for each operation add one line:

  • To move a file, write "src>dst". If the 'dst' file already exists it will be overwritten.

The success or failure of these operations will be recorded in the event log.

Contributions Welcome

If you are interested in joining the project, let me know. I'm always interested in more committers.

 

 

配置文件的格式请参考:https://kenai.com/projects/winsw/pages/ConfigurationSyntax 

我的一个例子如下

image

运行install后,在services.msc中可以看到这个服务

image

image

 

 

相关知识

在Windows系统里面,还有一类特殊的服务,他们都是用一个特殊的程序启动的(svchost),如下

image

那么,这又是怎么一回事情呢?有兴趣的童鞋可以参考  http://www.howtogeek.com/howto/windows-vista/what-is-svchostexe-and-why-is-it-running/

 

在Linux系统上面,也有一个类似的工具(而且更加强大),supervisor,有兴趣的童鞋可以参考

http://supervisord.org/introduction.html