How to Run an exe from windows service and stop service when the exe process quits?

24,385

Solution 1

You can use a BackgroundWorker for the threading, use Process.WaitForExit() to wait for the process to terminate until you stop your service.

You're right that you should do some threading, doing lots of work in the OnStart may render errors about not starting correctly from Windows when starting the service.

protected override void OnStart(string[] args)
{

    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerAsync();
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    Process p = new Process();
    p.StartInfo = new ProcessStartInfo("file.exe");
    p.Start();
    p.WaitForExit();
    base.Stop();
}

Edit You may also want to move the Process p to a class member and stop the process in the OnStop to make sure that you can stop the service again if the exe goes haywire.

protected override void OnStop()
{
    p.Kill();
}

Solution 2

You have to use a ServiceController to do it, it has a Stop method. Make sure your service has the CanStop property set to true.

Share:
24,385

Related videos on Youtube

xdumaine
Author by

xdumaine

Xander Dumaine I believe in inclusion, equality, and communication. I like solving technical problems to help further those principles. I'm currently enthusiastically working in React, GraphQL, DynamoDB, AWS Lambda, and Apollo. My CV is available at http://careers.stackoverflow.com/dumaine I'm also a rock climber, cyclist, and husband. I blog at http://blog.xdumaine.com and some other stuff is at http://www.xdumaine.com

Updated on September 16, 2020

Comments

  • xdumaine
    xdumaine over 3 years

    I am a complete beginner to working with windows services. I have a basic skeleton worked out for the service and I am currently doing this:

    protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            Process.Start(@"someProcess.exe");
        }
    

    just to fire-off the exe at the start of the program.

    However, I'd like to have the service stop itself when the process started from the exe quits. I'm pretty sure I need to do some sort of threading (something I am also a beginner with), but I'm not sure of the overall outline of how this works, nor the specific way to stop a process from within itself. Could you help me with the general process for this (i.e. start a thread from OnStart, then what...?)? Thanks.