Demonisation of a .NET Mono application on Linux

How to make a Linux-demon from a .NET Mono application.


Sample solution is available for download here

Main program starts a service process that will stay active in memory and will periodically activate a job – do something.


Creating a service (demon) application on Linux using Mono is the same simple as creating it on Windows with pure .NET. Here is a basic MSDN article Walkthrough: Creating a Windows Service Application in the Component Designer about it. The same code will run on both Windows and Linux and the only difference is how to run the service itself.
To run a mono application as a service it must be started with a help of a special tool called mono-service.


In my sample application I use Quartz.NET scheduler to run tasks periodically.

Program class

Service extends ServiceBase class with scheduler


Since I develop a service application debugging of it directly is complicated. I need a trick to simulate a service start. I can run OnStart() from a fake Main() method. This is described in an MSDN article How to: Debug the OnStart Method.

I do two modifications in the program:

  1. Surround main Main() method in the Program class with non-debug directives
  2. Add a second Main() method to the Service class and surround it with debug-only directives

Modified Program class

Second Main() method in the Service class

Now to debug the service switch to Debug configuration, set a breakpoint in the fake Main() and in the OnStart() methods.

Run the service

Specifies 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.

Stop the service

Just use kill UNIX command to terminate the process. Process id is stored in the lock file.

Start-stop script

Here is my simple start-stop script for a Mono service. Script must be included into C# solution and copied to the binary folder after build.
Script contains 3 procedures: usage, stop and start

Running script