使用NSTask和NSPipe会导致100%的CPU使用率 [英] Using NSTask and NSPipe causes 100% CPU usage
问题描述
我试图运行一个简单的bash脚本使用NSTask和直接输出到文本视图。一旦执行任务,我的应用程序的CPU使用率是100%,即使它是一个简单的 echo
(现在)。
I'm trying to run a simple bash script using NSTask and direct the output to a text view. Once the task is executed, the CPU usage of my app is 100%, even though it's a simple echo
(for now).
我创建了一个全新的项目来隔离问题:
I created a completely fresh project to isolate the issue:
@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
:
PipeTest[3933:2623] Read: <74657374 0a>
但是在我终止我的应用程序之前,CPU使用率保持在100%。
However the CPU usage stays at 100% until I terminate my app.
编辑:
时间剖面测试返回下面的列表,但我不知道如何解释This。
A Time Profiler test returns the list below, but I'm not sure how to interpret this.
>
推荐答案
文件句柄保持打开状态?
File handle left open?
@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使用率恢复正常。
Closing the file on the NSFileHandle
h
seems to return your CPU usage to normal.
这篇关于使用NSTask和NSPipe会导致100%的CPU使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!