使用NSTask和NSPipe会导致100%的CPU使用率

时间:2012-12-06 15:44:33

标签: objective-c macos cocoa nstask nspipe

我正在尝试使用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

它被正确执行,输出(作为NSData)与NSLog一起记录:

PipeTest[3933:2623] Read: <74657374 0a>

然而,在我终止我的应用程序之前,CPU使用率保持在100%。

修改

Time Profiler测试会返回下面的列表,但我不确定如何解释它。

enter image description here

2 个答案:

答案 0 :(得分:10)

文件句柄是否打开?

@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上的文件似乎会使您的CPU使用率恢复正常。

答案 1 :(得分:2)

如果应用程序写入的内容超过NSFileHandle的实现缓冲区(在我对El Capitan的观察中为4K),则建议的代码将无效。 [h readDataToEndOfFile]倾向于一次读取4K,因此该示例可能会过早地关闭缓冲区。对于您的处理程序来说,这是一个更强大且同样没有文档记录的方法:

NSData *data = [h readDataToEndOfFile];
if (data.length) {
  NSLog(@"Read: %@", data);
} else {
  [h closeFile];
}