• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 无法为标准输出管道触发 NSFileHandleDataAvailableNotification

[复制链接]
菜鸟教程小白 发表于 2022-12-13 11:12:18 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我们需要在 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap