[英]Read an endless output with nstask
Ok, here comes my problem. 好的,这是我的问题。 I have a program that tells me the value of a sensor, this program runs in a terminal and the output is just like that:
我有一个程序告诉我传感器的值,该程序在终端中运行,输出结果如下:
110 110
362 362
492 492
655 655
and so on....indefinitely with a rate of 4 lines (status) per second. 依此类推。...无限地以每秒4行(状态)的速率运行。 Then i need to display this values in real time in a level bar in my objective c program.
然后,我需要在目标c程序的水平栏中实时显示此值。 I try to use this code Execute a terminal command from a Cocoa app which is basically the use of nstask and pipes.
我尝试使用此代码从Cocoa应用程序执行终端命令,这基本上是nstask和管道的使用。 I realize that the program gets stuck when reaches data = [file readDataToEndOfFile];
我意识到,程序到达数据= [file readDataToEndOfFile]时会卡住; I think is because is waiting to finish the program or the output when this never ends.
我认为这是因为它在永远不会结束时正在等待完成程序或输出。 So, is there a way to get line by line in real time the status of this sensor?
那么,有没有一种方法可以实时地逐行获取该传感器的状态?
Here is my code, i just change the command for ping google.com due to the same endless output and similar rate. 这是我的代码,由于无尽的输出和相似的速率,我只是更改了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");
}
Get the NSFileHandle
for reading from your pipe and use waitForDataInBackgroundAndNotify
to be notified of new data. 获取
NSFileHandle
以便从管道中读取数据,并使用waitForDataInBackgroundAndNotify
通知新数据。 Each time you receive the notification, call waitForDataInBackgroundAndNotify
again to re-register. 每次收到通知时,再次调用
waitForDataInBackgroundAndNotify
进行重新注册。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.