【问题标题】:C# Window Service and Starting/Stopping cmd.exeC# 窗口服务和启动/停止 cmd.exe
【发布时间】:2011-06-10 19:39:55
【问题描述】:

我有一个 C# 窗口服务,它运行一个批处理文件 (.bat),而该文件又执行一个 java 应用程序。该服务运行 .bat 文件 (cmd.exe) 没有问题。但是,当我尝试停止窗口服务时,cmd.exe 进程并没有死。如果我再次启动服务,则会堆叠一个新的 cmd 进程。

如何杀死正在运行的 cmd.exe 进程?

代码:

    private const string BATCH_FILE_PATH_APPKEY = "Service_Batch_File_Path";
    private const string BATCH_FILE_DEFAULT = "Service.bat";

    private static Process _proc;
    private static bool _hasStarted = false;

    public AService()
    {
        InitializeComponent();
        _proc = new Process();
    }

    protected override void OnStart(string[] args)
    {
        try
        {

            string appDirectory = System.Windows.Forms.Application.ExecutablePath;
            appDirectory = appDirectory.Substring(0, appDirectory.LastIndexOf("\\"));
            string workingDirectory = appDirectory;
            string batchFilePath = string.Empty;
            batchFilePath = workingDirectory + "Service.bat";

            // Make sure it exists


            _proc.StartInfo = new ProcessStartInfo(batchFilePath);
            _proc.StartInfo.CreateNoWindow = true;
            _proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            _proc.Start();
            _hasStarted = true;
        }
        catch (System.Exception ex)
        {
            eventLog1.WriteEntry(ex.ToString() + "\n\nStack Trace:\n" + ex.StackTrace);
            OnStop();
        }
    }

    protected override void OnStop()
    {
        if (_hasStarted)
            _proc.CloseMainWindow();
            //_proc.Close(); 
    }

TIA, 亚历克斯。

【问题讨论】:

  • 应该把 _proc.Close() 注释掉吗?
  • 理想情况下,您可以告诉您的 java 应用程序优雅地终止。它自己关闭,它运行的 cmd.exe 关闭,每个人都很高兴。

标签: c# multithreading command-line windows-services


【解决方案1】:

_proc.Kill();

详见MSDN:Process.Kill Method

您可能会发现以下链接非常有用:Process.Close() is not terminating created process,c#

【讨论】:

    【解决方案2】:

    _proc.Kill () 将起作用....但它会孤立您的 Java 应用程序。我在启动第三个过程时做了类似的事情。您还需要知道要杀死哪个 java 进程。为此,您可以使用 ParentProcess 性能计数器。

    这里有一些使用ParentProcess performance counter的细节。

    另外,您打算在 Windows 版本上部署它吗? WindowsServer2008 似乎有一个 cmd.exe 和一个 conhost.exe。这可能会给您带来问题(同样可以通过了解父进程来解决。

    【讨论】:

      【解决方案3】:

      您是否在服务的关闭处理中尝试过_proc.Kill()?这是异步的,然后您应该致电 WaitForExit 给它一个不错的机会离开。记录此逻辑中的任何故障或异常以供调查。

      您还应该(为了清洁)在调用WaitForExit() 后恢复_proc.Close(),以确保为Process 正确调用Dispose()。我知道您的服务即将退出,但这是一个好习惯,这意味着如果您决定将来更动态地管理子进程,您就不太可能泄漏。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-27
        • 2013-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多