无法为stdout管道触发NSFileHandleDataAvailableNotification

时间:2015-10-04 19:12:42

标签: ios objective-c nsnotificationcenter nsfilehandle

我们需要在iOS中捕获stdout,因为我们正在使用通过stdin / stdout进行通信的开源项目

这有效:

NSPipe *pipe = [NSPipe pipe];
NSFileHandle *readh = [pipe fileHandleForReading];

dup2([[pipe fileHandleForWriting] fileDescriptor], fileno(stdout));

[@"Hello iOS World!" writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:nil];

NSData *data = [readh availableData];
NSLog(@"%d", [data length]);
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@%@", @"stdout captured:", str);

控制台打印:

2015-10-04 12:03:29.396 OpeningExplorer[857:42006] 16
2015-10-04 12:03:29.397 OpeningExplorer[857:42006] stdout captured:Hello iOS World!

但是上面的例子阻止了。为什么以下异步代码不起作用?

    NSPipe *pipe = [NSPipe pipe];
    NSFileHandle *readh = [pipe fileHandleForReading];

    dup2([[pipe fileHandleForWriting] fileDescriptor], fileno(stdout));

    [[NSNotificationCenter defaultCenter] addObserverForName:NSFileHandleDataAvailableNotification
                                                        object:readh
                                                       queue:[NSOperationQueue mainQueue]
                                                    usingBlock:^(NSNotification *note) {
        NSFileHandle *fileHandle = (NSFileHandle*) [note object];
        NSLog(@"inside listener");
        NSData *data = [fileHandle availableData];
        NSLog(@"%d", [data length]);
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@%@", @"stdout captured:", str);

    }];
    [readh waitForDataInBackgroundAndNotify];

    [@"Hello iOS World!" writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:nil];

通知代码块似乎没有被调用 - 控制台没有输出任何东西

1 个答案:

答案 0 :(得分:1)

来自waitForDataInBackgroundAndNotify上的Apple's documentation:“您必须从具有活动运行循环的线程调用此方法。”

这意味着您无法在NSOperationQueueNSThread内拨打此电话。因此,请确保此代码是从主UI线程运行的,而不是后台线程。

(如果有人像我一样懒,并且不想通过评论解析以找到答案,则张贴。)