Is it possible to Kick off a java process under Windows Service with C#?

Posted by Wing C. Chen on Stack Overflow See other posts from Stack Overflow or by Wing C. Chen
Published on 2010-05-21T11:26:18Z Indexed on 2010/05/21 11:30 UTC
Read the original article Hit count: 240

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about windows-services

Related posts about c#