如何创建一个启动和停止多个'exe'/'bat的Windows服务

问题描述 投票:0回答:1

我正在尝试创建一个Windows服务,将管理启动多个exes / bat文件。

到目前为止,我已经遵循这个guide,并能够使用以下代码启动exe。但是,当我停止服务时,衍生的exe似乎是分离的,我不确定如何以编程方式杀死它。

最终我想开始和停止许多不同的bats和exes。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Runtime.InteropServices;

namespace SomeService
{
  public partial class Service1 : ServiceBase
  {

    public Service1()
    {
      InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
      Process.Start("C:\\Users\\JohnnySmalls\\SomeProgram\\bin\\theExe.exe");
    }

    protected override void OnStop()
    {
      // Need to close process, I don't have a reference to it though
      // Process.Close();
    }
  }
}
c# windows service
1个回答
0
投票

你可以做这样的事情

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.Threading.Tasks;
    using System.Timers;
    using System.Runtime.InteropServices;

    namespace SomeService
    {

      public partial class Service1 : ServiceBase
      {
        private List<Process> _processes;
        public Service1()
        {
            InitializeComponent();
            _processes = new List<Process>();
        }

        protected override void OnStart(string[] args)
        {
          var process = Process.Start("C:\\Users\\JohnnySmalls\\SomeProgram\\bin\\theExe.exe");
          _processes.Add(process);
        }

        protected override void OnStop()
        {
          // Need to close process, I don't have a reference to it though
          // Process.Close();
            foreach(var process in _processes) {
                process.Close();
            }
        }
      }
    }
© www.soinside.com 2019 - 2024. All rights reserved.