objective-c - echo 不适用于 NSTask 和 readInBackgroundAndNotify

标签 objective-c cocoa echo nstask nsfilehandle

我有以下 Obj-C 代码及其日志输出。谁能告诉我为什么我没有从 NSFileHandle 获得任何输出?

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [self performSelectorInBackground:@selector(startTask:) withObject:nil];
}

- (void) startTask: (id) sender
{
    NSPipe *pipe = [[NSPipe alloc] init];
    NSFileHandle *fh = pipe.fileHandleForReading;

    [fh readInBackgroundAndNotify];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(output:) name:NSFileHandleReadCompletionNotification object:fh];

    NSTask *echoTask = [[NSTask alloc] init];

    echoTask.standardOutput = pipe;
    echoTask.standardError = [[NSPipe alloc] init];
    echoTask.launchPath = @"/bin/echo";
    echoTask.arguments = @[@"hello world!"];

    NSLog(@"launching...");
    [echoTask launch];
    [echoTask waitUntilExit];
    NSLog(@"finished.");
}

- (void) output:(NSNotification *)notification
{
    NSFileHandle *fh = notification.object;
    NSLog(@"fh: %@", fh);

    NSString *output = [[NSString alloc] initWithData:[fh readDataToEndOfFile] encoding:NSUTF8StringEncoding];

    NSLog(@"output: '%@'", output);
}

@end

日志:

2014-12-16 10:19:58.154 SubProcess2[14893:704393] launching...
2014-12-16 10:19:58.165 SubProcess2[14893:704393] fh: <NSConcreteFileHandle: 0x6080000e9e80>
2014-12-16 10:19:58.165 SubProcess2[14893:704393] output: ''
2014-12-16 10:19:58.166 SubProcess2[14893:704393] finished.

如果我同步执行或使用 https://stackoverflow.com/a/16274541/1015200 中的方法我可以让它发挥作用。 任何其他技术和变体(例如在没有 PerformSelectorInBackground 的情况下启动任务)都失败了。 我真的很想看看是否可以使用通知让它工作。 因此,如果我能得到任何帮助那就太好了。

最佳答案

已读取的数据将传递到 userInfo 字典中 NSFileHandleNotificationDataItem 键下的通知,您应该访问该通知而不是尝试读取更多数据。例如。像这样:

- (void) output:(NSNotification *)notification
{
   NSString *output = [[NSString alloc]
                      initWithData:notification.userInfo[NSFileHandleNotificationDataItem] 
                          encoding:NSUTF8StringEncoding];

   NSLog(@"output: '%@'", output);
}

HTH

关于objective-c - echo 不适用于 NSTask 和 readInBackgroundAndNotify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27511594/

相关文章:

ios - 我怎样才能把角标(Badge)图标放在菜单栏的应用程序中?

ios - performSelector 可能会导致泄漏,因为它的选择器是未知的

ios - Objective C 中的关系对象

string - bash shell脚本将字符串与句点字符连接起来

ios - Cloudkit我们可以修改公共(public)数据库的数据吗

swift - 在 xib Controller 中注入(inject)依赖项

cocoa - 是否行程矩形 : of NSBezierPath always draw a transparent rect? (Cocoa OSX)

objective-c - 同一类的不同实例之间共享属性

php - 在查询中使用 echo

Swift Shell 命令在文件中回显