内容简介:http://stackoverflow.com/questions/6931732/nstasks-real-time-output
我有一个 PHP 脚本具有多个sleep()命令.我想在我的应用程序中执行它与NSTask.我的脚本如下所示:
echo "first\n"; sleep(1); echo "second\n"; sleep(1); echo "third\n";
我可以使用通知异步执行我的任务:
- (void)awakeFromNib { NSTask *task = [[NSTask alloc] init]; [task setLaunchPath: @"/usr/bin/php"]; NSArray *arguments; arguments = [NSArray arrayWithObjects: @"-r", @"echo \"first\n\"; sleep(1); echo \"second\n\"; sleep(1); echo \"third\n\";", nil]; [task setArguments: arguments]; NSPipe *p = [NSPipe pipe]; [task setStandardOutput:p]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskExited:) name:NSTaskDidTerminateNotification object:task]; [task launch]; } - (void)taskExited:(NSNotification *)notif { NSTask *task = [notif object]; NSData *data = [[[task standardOutput] fileHandleForReading] readDataToEndOfFile]; NSString *str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSLog(@"%@",str); }
我的输出是(当然2秒后):
2011-08-03 20:45:19.474 MyApp[3737:903] first second third
我的问题是:打印后如何立即得到这三个字?
当脚本将数据写入其输出时,可以使用NSFileHandle的waitForDataInBackgroundAndNotify方法来接收通知.但是,如果解释器立即发送字符串,这将只起作用.如果缓冲区输出,则在任务退出后,您将收到一条通知.
- (void)awakeFromNib { NSTask *task = [[NSTask alloc] init]; [task setLaunchPath: @"/usr/bin/php"]; NSArray *arguments; arguments = [NSArray arrayWithObjects: @"-r", @"echo \"first\n\"; sleep(1); echo \"second\n\"; sleep(1); echo \"third\n\";", nil]; [task setArguments: arguments]; NSPipe *p = [NSPipe pipe]; [task setStandardOutput:p]; NSFileHandle *fh = [p fileHandleForReading]; [fh waitForDataInBackgroundAndNotify]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedData:) name:NSFileHandleDataAvailableNotification object:fh]; [task launch]; } - (void)receivedData:(NSNotification *)notif { NSFileHandle *fh = [notif object]; NSData *data = [fh availableData]; if (data.length > 0) { // if data is found, re-register for more data (and print) [fh waitForDataInBackgroundAndNotify]; NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@" ,str); } }
http://stackoverflow.com/questions/6931732/nstasks-real-time-output
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- php nginx 实时输出
- 实时输出前端源代码,折腾大半年的开源项目 sparrow-js
- 2. Python中的基本输入、输出、格式化输出
- console 输出对象
- 多种格式数据输出
- Java输入输出挂
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Real-Time Rendering, Third Edition
Tomas Akenine-Moller、Eric Haines、Naty Hoffman / A K Peters/CRC Press / 2008-7-25 / USD 102.95
Thoroughly revised, this third edition focuses on modern techniques used to generate synthetic three-dimensional images in a fraction of a second. With the advent or programmable shaders, a wide varie......一起来看看 《Real-Time Rendering, Third Edition》 这本书的介绍吧!