繁体   English   中英

C# Window 服务和启动/停止 cmd.exe

[英]C# Window Service and Starting/Stopping cmd.exe

我有一个运行批处理文件(.bat)的 C# Window 服务,该文件又执行 java 应用程序。 该服务运行 .bat 文件 (cmd.exe) 没有问题。 但是,当我尝试停止 window 服务时,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.Kill();

请参阅 MSDN 中的详细信息: Process.Kill 方法

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

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

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

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

以下是有关使用ParentProcess 性能计数器的一些详细信息。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM