使用waitUntilExit挂起NSTask [英] Hanging NSTask using waitUntilExit
问题描述
我需要同步使用NSTask,但是我发现我的任务有时挂在"waitUntilExit"命令下.我想知道是否有一种优美的方法(一种错误处理方法)来终止挂起的任务,以便我可以重新启动另一个任务?
I need to use NSTask synchronously, however I find that occasionally my task hangs under the 'waitUntilExit' command. I wonder if there is a graceful way--an error handling method--to terminated the hanging task so I can re-launch another?
推荐答案
请注意,如果通过 NSTask
运行的任务填充了输出管道,则该进程将挂起,从而有效地阻塞了 waitUntilExit
返回.
Note that if the task being run via NSTask
fills the output pipe then the process will hang, effectively blocking waitUntilExit
from returning.
您可以通过致电
[task.standardOutput.fileHandleForReading readDataToEndOfFile];
致电
[task waitUntilExit];
这将导致读取输出管道的数据,直到写入输出管道的进程将其关闭为止.
This will cause the output pipe's data to be read until the process writing to the output pipe closes it.
示例代码演示了该问题和各种解决方案:
Example code demonstrating the issue and various solutions:
https://github.com/lroathe/PipeTest
这篇关于使用waitUntilExit挂起NSTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!