1. 程式人生 > >如何利用mono把.net windows service程式遷移到linux上

如何利用mono把.net windows service程式遷移到linux上

寫在最前:之所以用要把windows程式遷移到Linux上,主要是由於一些成本問題,這個就不多解釋了。

如何把之前用.net寫的windows服務程式遷移到linux上執行。答案是有很多種的,今天我只提一下mono(我只實驗了mono,呵呵)。

如何在Linux部署mono,併成功的執行.net程式,還請大家多多查詢吧,我在這方面也只是搭建成功了,遇到的問題不足夠多,就不誤導大家了。

用mono來在Linux執行一個.net程式還是很容易的,但如何執行一個後臺服務程式呢,今天也是費了九牛二虎之力,最後借鑑一下stackoverflow中的一個回答來詮釋這個難題吧。

Under Linux, 

deamons are simple background processes. No special control methods (e.g start()stop()) are used as in Windows. Build your service as a simple (console) application, and run it in the background. Use a tool like daemonize to run a program as a Unix daemon, and remember to specify mono as the program to be activated.

As noted by others, mono-service is a host to run services built with the ServiceProcess assembly. Services built for Windows can use this method to run unmodified under Linux. You can control the service by sending signals to the process (see man page).

我英文不是太好,只能大概理解其中的意思。裡邊的滋味大家可以自己細細品味。

大致意思就是說,第一種方式:在Linux下可以把windows服務改造成一個控制檯程式來執行。第二種方式:用mono-service來執行windows的服務程式。前提是你這個程式是有.net寫成的。

mono-service執行時引數又該如何配置呢?

命令格式:mono-service [options] program.exe

-d:DIRECTORYUse this option to specify the working directory for the service. The default is the current directory.

-l:LOCKFILESpecifies the file to use for locking, the default is a filename constructed in /tmp based on the name of the program that hosts the service.

-m:MESSAGEName to show in the syslog.

-n:NAMEUse this to specify the service to be launched (if the program contains more than one service). The default is to run the first defined service.

--debug:Use this option to prevent mono-service from redirecting stdin and stdout and prevent the program to be sent to the background. Equivalent to

--no-daemon:Use this option to prevent mono-service from redirecting stdin and stdout and prevent the program to be sent to the background. Equivalent to --debug.

例:mono-service -l:/var/run/Myservice-lock.pid MyService.exe  (這個-l引數一定要加上

控制服務(這幾種操作的區別請參考windows的使用方式,這裡我就不做過多解釋了):

暫停:kill -USR1 `cat <lock file>`

繼續: kill -USR2 `cat <lock file>`

停止: kill `cat <lock file>`

 這裡的不是單引號,是數字1左邊的那個點號。(夠坑)

注意:Use mono-service to run services that use the 1.0 assemblies and use mono-service2 to run services that use the 2.0 assemblies.

mono-service可以執行.net 1.0的程式集,mono-service2可以執行.net 2.0的程式集。

對上面刪除的內容做一下糾正,之前用的2.0的程式做的測試,沒有發現這個問題。

後來翻了一些資料發現:mono-service已經不再支援.net程式了,mono-service2支援的還是.net2.0的程式。特別說明mono-service支援的是4.5的程式了,至於它對4.0支援如何,自己實驗一下吧,我就不一一實驗了。下面我為這個說法提供一些佐證: