无法杀死进程.net

时间:2012-11-17 09:28:47

标签: .net process cmd

我似乎用以下代码创建了一个“不朽”的过程:

System.Diagnostics.ProcessStartInfo test = new ProcessStartInfo("cmd", " /c " + aCommandLine); //aCommandLine is : ruby test.rb
test.CreateNoWindow = true;
test.RedirectStandardError = true;
test.RedirectStandardOutput = true;
test.UseShellExecute = false;
test.WorkingDirectory = System.IO.Path.GetDirectoryName(aRTextFilePath);
System.Diagnostics.Process aProcess = Process.Start(test);
aProcess.EnableRaisingEvents = true;
aProcess.Exited += new EventHandler(aProcess_Exited);
try
{
    //read synchronously to get the port number
    string aPortInformationLine = aProcess.StandardOutput.ReadLine();
    if (!aProcess.HasExited)
    {
        aProcess.Kill();
        Debug.Print("Process Has Exited");
    }
    //return true;
    errorOut = String.Format("Could not start process with command line : {0} from .rtext file {1}", aCommandLine, aRTextFilePath);
    port = -1;
    return false;
}
catch (Win32Exception ex)
{
    Debug.WriteLine(ex.NativeErrorCode.ToString());
    errorOut = String.Format("Could not start process with command line : {0} from .rtext file {1}. Error : {2}", aCommandLine, aRTextFilePath, ex.NativeErrorCode.ToString());
}
catch (Exception ex)
{
    Debug.WriteLine(ex.Message);
    errorOut = String.Format("Could not start process with command line : {0} from .rtext file {1}. Error : {2}", aCommandLine, aRTextFilePath, ex.Message);
}

所以我使用cmd来启动某种类型的ruby服务器。该过程开始,我能够从新创建的进程中读取输出。但是,当执行kill命令时,不会抛出任何异常,但ruby进程不会死亡。

这与使用cmd有什么关系吗?我做错了什么吗?感谢

修改

我使用了进程资源管理器并在kill之前和之后拍了2张照片:

在:

BeforeKill 后:

AfterKill

因此,当cmd.exe死亡时,ruby以某种方式设法继续生活,看到另一天......

EDIT2:

回答我的问题:Kill process tree programmatically in C#

3 个答案:

答案 0 :(得分:1)

你希望杀死命令处理器也会杀死它启动的任何进程是一个空闲的,Windows就是这样不行。在Windows中有一种机制,作业对象,但你不想去那里。只是不要使用cmd.exe,它不会添加任何值。直接启动ruby.exe。

答案 1 :(得分:0)

来自MSDN:

Kill方法异步执行。在调用Kill方法之后,调用WaitForExit方法以等待进程退出,或者检查HasExited属性以确定进程是否已退出。

答案 2 :(得分:0)

请检查进程是否有任何未声明为后台线程的线程。而且这个过程可能有任何无限循环..

相关问题