[英]Using NSTask and NSPipe causes 100% CPU usage
我正在尝试使用NSTask运行一个简单的bash脚本,并将输出定向到文本视图。 执行任务后,我的应用程序的CPU使用率为100%,即使它是一个简单的echo
(目前)。
我创建了一个全新的项目来隔离问题:
@interface AppDelegate ()
@property (nonatomic) NSTask *task;
@property (nonatomic) NSPipe *pipe;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
self.pipe = [NSPipe pipe];
self.pipe.fileHandleForReading.readabilityHandler = ^(NSFileHandle *h) {
NSLog(@"Read: %@", [h readDataToEndOfFile]);
};
self.task = [[NSTask alloc] init];
self.task.launchPath = @"/bin/bash";
self.task.arguments = @[@"-c", @"echo test"];
self.task.standardOutput = self.pipe;
[self.task launch];
}
@end
它被正确执行并且使用NSLog
记录输出(作为NSData
):
PipeTest[3933:2623] Read: <74657374 0a>
但是,在我终止我的应用程序之前,CPU使用率保持在100%。
编辑:
Time Profiler测试返回下面的列表,但我不知道如何解释这个。
文件句柄是否打开?
@interface AppDelegate ()
@property (nonatomic) NSTask *task;
@property (nonatomic) NSPipe *pipe;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
self.pipe = [NSPipe pipe];
self.pipe.fileHandleForReading.readabilityHandler = ^(NSFileHandle *h) {
NSLog(@"Read: %@", [h readDataToEndOfFile]);
[h closeFile];
};
self.task = [[NSTask alloc] init];
self.task.launchPath = @"/bin/bash";
self.task.arguments = @[@"-c", @"echo test"];
self.task.standardOutput = self.pipe;
[self.task launch];
}
关闭NSFileHandle
上的文件h
似乎NSFileHandle
CPU使用率恢复正常。
如果应用程序写入的内容超过NSFileHandle的实现缓冲区(在我对El Capitan的观察中为4K),则建议的代码将不起作用。 [h readDataToEndOfFile]倾向于一次读取4K,因此该示例可能会过早地关闭缓冲区。 对于您的处理程序,一个更强大且同样未记录的方法是:
NSData *data = [h readDataToEndOfFile];
if (data.length) {
NSLog(@"Read: %@", data);
} else {
[h closeFile];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.