小编Act*_*lis的帖子

从Unix命令读取NSTask/NSPipe

我正在编写一个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,但管道似乎从来没有得到任何数据.有什么方法可以"戳" NSTaskNSPipe通过刷新数据?

编辑:用-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)

cocoa objective-c nstask nspipe

6
推荐指数
1
解决办法
3559
查看次数

标签 统计

cocoa ×1

nspipe ×1

nstask ×1

objective-c ×1