微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/c/119184.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐