Using NSTask and NSPipe results in 100% CPU usage

I am trying to run a simple bash script using NSTask and direct the output to a text view. When the task is completed, downloading my application to the PDA is 100%, although this is a simple echo (for now).

I created a completely new project to isolate the problem:

 @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 

It executes correctly, and the output (like NSData ) is logged using NSLog :

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

However, CPU usage remains at 100% until I quit my application.

EDIT:

The Time Profiler test returns the list below, but I'm not sure how to interpret this.

enter image description here

+7
source share
2 answers

Does the file handle remain 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]; } 

Closing a file on NSFileHandle h like using your processor normally.

+9
source

The proposed code will not work if the application writes more than the NSFileHandle implementation buffer (4K in my observation on El Capitan). [h readDataToEndOfFile] tends to read 4K at a time, so this example may close the buffer prematurely. A more robust and equally undocumented approach for your handler is as follows:

 NSData *data = [h readDataToEndOfFile]; if (data.length) { NSLog(@"Read: %@", data); } else { [h closeFile]; } 
+2
source

All Articles