views:

94

answers:

2

I would like to wrap a java program into a windows service with C# using System.ServiceProcess.ServiceBase. So I came up with the following code:

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
    System.ServiceProcess.ServiceBase.Run(new JavaLauncher());
}
protected override void OnStart(string[] args)
{
    Thread _thread;
    _thread = new Thread(StartService);
    _thread.Start();
    base.OnStart(args);
}
protected override void OnStop()
{
    Thread _thread;
    _thread = new Thread(StopService);
    _thread.Start();
    base.OnStop();
}
static public void StartService()
{
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.EnableRaisingEvents = false;
    proc.StartInfo.FileName = "javaw";
    proc.StartInfo.Arguments = config.generateLaunchCommand();
    proc.Start();
}
static public void StopService()
{
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.EnableRaisingEvents = false;
    proc.StartInfo.FileName = "javaw";
    proc.StartInfo.Arguments = "-jar stop.jar";
    proc.Start();
}

Firstly I had to use Threads in OnStart and OnStop. If not, an exception occurs complaining that the service is terminated because of doing nothing.

Secondly, the service can be hooked up to windows smoothly. However, the service terminates a short while after it is started. I looked into the process monitor, only the service process stays alive for that short while, the javaw process never showed up, however. Is there anyone who knows how this can be fixed?

It works fine in an ordinary console environment. I think it has something to do with Windows service.

+1  A: 

I would recommend you use an open source solution instead.

See this post http://stackoverflow.com/questions/68113/how-to-create-a-windows-service-from-java-app
I would suggest going with this http://sourceforge.net/projects/yajsw/

Romain Hippeau
well... I did a survey on all the available tools. They either have A but miss B, or have B but miss A. Thank you though for your suggestion.
Winston Chen
+1  A: 

That the Java process does not show up does not mean it did not start. It could've started and shut down right away. Try redirecting the stdout/stderr to see what's happening.

Also the proc variable Within both StartService and stopservice methods is a local variable. When it goes out of scope, your process object is garbage collected. I wonder if this causes your java process to die

mfeingold
ohm yeah.. I did not think of the local variable issue. I will give it a try. Thank you very much.
Winston Chen
It turns out that the process termination problem was due to a folder path mismatch. I assumed that the path I specified in the program is relative to the location of the folder that contains the .exe file. However, in windows service, all relative path are relative to C:\WINDOWS\system32.
Winston Chen