使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM