7

NSTask を使用して簡単な bash スクリプトを実行し、出力をテキスト ビューに表示しようとしています。タスクが実行されると、アプリの CPU 使用率は単純ですがecho(今のところ) 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

正しく実行され、出力 ( としてNSData) が次のように記録されますNSLog

PipeTest[3933:2623] Read: <74657374 0a>

ただし、アプリを終了するまで CPU 使用率は 100% のままです。

編集:

Time Profiler のテストでは以下のリストが返されますが、これをどのように解釈すればよいかわかりません。

ここに画像の説明を入力

4

2 に答える 2

11

ファイルハンドルが開いたまま?

@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 hCPU 使用率が通常に戻るようです。

于 2012-12-06T17:09:47.487 に答える