objective-c – 使用NSTask和NSPipe会导致100%的CPU使用率

我正在尝试使用NSTask运行一个简单的bash脚本,并将输出定向到文本视图.执行任务后,我的应用程序的cpu使用率为100%,即使它是一个简单的回声(目前).

我创建了一个全新的项目来隔离问题:

@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似乎会将cpu使用率恢复正常.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...