繁体   English   中英

使用nstask读取无尽的输出

[英]Read an endless output with nstask

好的,这是我的问题。 我有一个程序告诉我传感器的值,该程序在终端中运行,输出结果如下:

110

362

492

655

依此类推。...无限地以每秒4行(状态)的速率运行。 然后,我需要在目标c程序的水平栏中实时显示此值。 我尝试使用此代码从Cocoa应用程序执行终端命令,这基本上是nstask和管道的使用。 我意识到,程序到达数据= [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");
}

获取NSFileHandle以便从管道中读取数据,并使用waitForDataInBackgroundAndNotify通知新数据。 每次收到通知时,再次调用waitForDataInBackgroundAndNotify进行重新注册。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM