【问题标题】:Read an endless output with nstask使用 nstask 读取无穷无尽的输出
【发布时间】:2013-10-19 22:19:03
【问题描述】:

好的,我的问题来了。我有一个程序告诉我传感器的值,这个程序在终端中运行,输出是这样的:

110

362

492

655

等等....以每秒 4 行(状态)的速率无限期地进行。 然后我需要在我的目标 c 程序的级别栏中实时显示这些值。 我尝试使用这段代码Execute a terminal command from a Cocoa app,它基本上是使用nstask 和管道。 我意识到程序在到达 data = [file readDataToEndOfFile]; 时卡住了。我认为是因为当这永远不会结束时正在等待完成程序或输出。那么,有没有办法实时逐行获取这个传感器的状态呢?

这是我的代码,由于相同的无穷输出和相似的速率,我只是更改了 ping google.com 的命令。

- (void) epocSender
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/sbin/ping"];
NSArray *arguments;arguments = [NSArray arrayWithObjects: @"google.com", nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedData:) name:NSFileHandleDataAvailableNotification object:file];
[file waitForDataInBackgroundAndNotify];
}

- (void)receivedData:(NSNotification *)notif {
    NSLog(@"notification received");
}

【问题讨论】:

    标签: objective-c pipe nstask


    【解决方案1】:

    获取NSFileHandle 用于从您的管道中读取数据,并使用waitForDataInBackgroundAndNotify 接收新数据通知。每次收到通知,请再次拨打waitForDataInBackgroundAndNotify重新注册。

    【讨论】:

    • 我已经尝试(3 天)使用 readInBackgroundAndNotify 但不知何故我从来没有收到通知,所以我不能调用 nsnotification 方法。我从这篇文章中得到了如何使用它的提示http://stackoverflow.com/questions/6931732/nstasks-real-time-output/6931865#comment8260186_6931865 ..请帮帮我!
    • 我已更新为waitForDataInBackgroundAndNotify,因为在下一组数据可用之前总是有延迟。如果仍有问题,请出示您的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 2023-03-20
    • 2016-09-22
    • 2020-03-28
    • 2013-09-23
    • 2012-07-10
    相关资源
    最近更新 更多