NSTask的实时输出 [英] NSTask's real-time output
问题描述
我有一个包含多个sleep()
命令的PHP脚本.我想在我的应用程序中使用NSTask
执行它.我的脚本如下:
I have a PHP script which has mutliple sleep()
commands. I would like to execute it in my application with NSTask
. My script looks like this:
echo "first\n"; sleep(1); echo "second\n"; sleep(1); echo "third\n";
我可以使用通知异步执行任务:
I can execute my task asynchronously using notifications:
- (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秒钟后):
My output is (after 2 seconds, of course):
2011-08-03 20:45:19.474 MyApp[3737:903] first
second
third
我的问题是:这些单词打印后如何立即获得三个单词?
推荐答案
当脚本将数据写入其输出时,可以使用NSFileHandle的waitForDataInBackgroundAndNotify
方法接收通知.但是,只有在解释器立即发送字符串的情况下,这才起作用.如果它缓冲输出,则在任务退出后您会收到一条通知.
You can use NSFileHandle's waitForDataInBackgroundAndNotify
method to receive a notification when the script writes data to its output. This will only work, however, if the interpreter sends the strings immediately. If it buffers output, you will get a single notification after the task exits.
- (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);
}
}
这篇关于NSTask的实时输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!