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