我正在编写一个Cocoa应用程序,它需要执行一个UNIX程序并逐行读取它的输出.我设置了NSTask和NSPipe:
task = [[NSTask alloc] init];
pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
//... later ...
[task setArguments:...];
[task setLaunchPath:@"..."];
[task launch];
handle = [[task fileHandleForReading] retain];
Run Code Online (Sandbox Code Playgroud)
该命令不会终止,直到程序通知它为止[task terminate].我试图从手柄读取几种方法,如-readInBackgroundAndNotify,while([(data = [handle availableData]) length] > 0)和-waitForDataInBackgroundAndNotify,但管道似乎从来没有得到任何数据.有什么方法可以"戳" NSTask或NSPipe通过刷新数据?
编辑:用-readInBackgroundAndNotify:
[handle readInBackgroundAndNotify];
notification_block_t handlerBlock =
^(NSNotification *notification) {
NSData *data = [[notification userInfo]
objectForKey: NSFileHandleNotificationDataItem];
/*... do stuff ...*/
[self addNotification: handle block: handlerBlock];
};
[self addNotification: handler block: handlerBlock]; …Run Code Online (Sandbox Code Playgroud)