Process.kill 好像不行
Process.kill does not seem to work
以下代码在最后调用 WaitForExit 时挂起。如果我删除 1 秒长睡眠,它会干净地终止。有人可以告诉我该怎么做,以便在我调用 Kill() 后不久该进程就会终止吗?非常感谢。
let processStartInfo = System.Diagnostics.ProcessStartInfo("c:/cygwin/bin/bash.exe", "-c yes")
processStartInfo.CreateNoWindow <- true
processStartInfo.UseShellExecute <- false
processStartInfo.RedirectStandardOutput <- true
processStartInfo.RedirectStandardInput <- false
processStartInfo.RedirectStandardError <- true
use proc = new System.Diagnostics.Process ()
proc.StartInfo <- processStartInfo
let f _ = ()
proc.OutputDataReceived.Add f
proc.ErrorDataReceived.Add f
if not (proc.Start()) then
failwithf "Could not start"
proc.BeginErrorReadLine ()
proc.BeginOutputReadLine ()
// the process terminates fine without this
System.Threading.Thread.Sleep (1000)
printf "Waiting to die"
proc.Kill () // this does not seem to work
proc.CancelOutputRead ()
proc.CancelErrorRead ()
proc.WaitForExit() // execution gets stuck here, apparently forever
我不懂 F#,但是这段代码有一些非常奇怪的地方; Process.Read()
是一个阻塞调用,所以你要么必须让它们异步,要么调用 .ReadToEnd()
来代替,如果你想等到重定向完成。我会使用 proc.Dispose()
或将其放在 C# 中的 using
块中,而不是调用 proc.kill()
,这应该在 WaitForExit()
.
之后完成
查看我对 Opening a DOS Console 的回答。
另请查看 this reply 说如果同时重定向 stdOut 和 stdErr,则必须至少使一个异步。
以下代码在最后调用 WaitForExit 时挂起。如果我删除 1 秒长睡眠,它会干净地终止。有人可以告诉我该怎么做,以便在我调用 Kill() 后不久该进程就会终止吗?非常感谢。
let processStartInfo = System.Diagnostics.ProcessStartInfo("c:/cygwin/bin/bash.exe", "-c yes")
processStartInfo.CreateNoWindow <- true
processStartInfo.UseShellExecute <- false
processStartInfo.RedirectStandardOutput <- true
processStartInfo.RedirectStandardInput <- false
processStartInfo.RedirectStandardError <- true
use proc = new System.Diagnostics.Process ()
proc.StartInfo <- processStartInfo
let f _ = ()
proc.OutputDataReceived.Add f
proc.ErrorDataReceived.Add f
if not (proc.Start()) then
failwithf "Could not start"
proc.BeginErrorReadLine ()
proc.BeginOutputReadLine ()
// the process terminates fine without this
System.Threading.Thread.Sleep (1000)
printf "Waiting to die"
proc.Kill () // this does not seem to work
proc.CancelOutputRead ()
proc.CancelErrorRead ()
proc.WaitForExit() // execution gets stuck here, apparently forever
我不懂 F#,但是这段代码有一些非常奇怪的地方; Process.Read()
是一个阻塞调用,所以你要么必须让它们异步,要么调用 .ReadToEnd()
来代替,如果你想等到重定向完成。我会使用 proc.Dispose()
或将其放在 C# 中的 using
块中,而不是调用 proc.kill()
,这应该在 WaitForExit()
.
查看我对 Opening a DOS Console 的回答。
另请查看 this reply 说如果同时重定向 stdOut 和 stdErr,则必须至少使一个异步。