I'm running a command via NSTask that generates a very large amount of output. I created a pipe connected to standard output and am using waitForDataInBackgroundAndNotify and consuming the data with availableData. However it appears that all of the output is being buffered as the memory allocated by the app grows continuously. How can I purge / consume the data being sent to stdout? Here is the code I'm using:
- (void)runCommand:(NSString *)commandToRun
{
self.task = [[NSTask alloc] init];
[self.task setLaunchPath: @"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
@"-c" ,
[NSString stringWithFormat:@"%@", commandToRun],
nil];
[self.task setArguments: arguments];
NSPipe *pipe = [NSPipe pipe];
[self.task setStandardOutput:pipe];
NSFileHandle *fh = [pipe fileHandleForReading];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedData:) name:NSFileHandleDataAvailableNotification object:fh];
[fh waitForDataInBackgroundAndNotify];
[self.task launch];
}
- (void)receivedData:(NSNotification *)notification
{
NSFileHandle *fh = [notification object];
NSData *data = [fh availableData];
// do stuff...
[fh waitForDataInBackgroundAndNotify];
}