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

前端之家收集整理的这篇文章主要介绍了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使用率恢复正常.

原文链接:https://www.f2er.com/c/119184.html

猜你在找的C&C++相关文章