我正在通过NSTask运行一个生成大量输出的命令。我创建了一个连接到标准输出的管道,并使用waitForDataInBackgroundAndNotify并使用availableData消耗数据。但是,当应用程序分配的内存不断增长时,似乎所有输出都被缓冲。如何清除/使用发送到stdout的数据?这是我正在使用的代码:
- (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];
}