OGeek|极客世界-中国程序员成长平台

标题: ios - 无法为标准输出管道触发 NSFileHandleDataAvailableNotification [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:12
标题: ios - 无法为标准输出管道触发 NSFileHandleDataAvailableNotification

我们需要在 iOS 中捕获标准输出,因为我们使用的是通过标准输入/标准输出进行通信的开源项目

这行得通:

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];

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



Best Answer-推荐答案


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

这意味着您不能从 NSOperationQueueNSThread 中调用它。因此,请确保此代码是从您的主 UI 线程而不是后台线程运行的。

(发布以防有人像我一样懒惰并且不想解析评论以找到答案..)

关于ios - 无法为标准输出管道触发 NSFileHandleDataAvailableNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32937344/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4