osx – NSTask的实时输出

栏目: IOS · 发布时间: 5年前

内容简介: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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

走出电商困局

走出电商困局

黄若 / 东方出版社 / 2013-11-1 / 38.00

高速增长的时代趋于结束,迅猛运转的加速器早已锈蚀 这是一场转型,更是一次新的机遇 《走出电商困局》是本年度最畅销管理书籍《我看电商》作者黄若的最新力作,意在深度剖析电商行业发展 ,破解电商困局。经历过10年超常规的快速增长,电商行业即将进入较为平稳的发展期。多年来这个行业不断融资不断烧钱却大多无法盈利的怪圈怎样突破?在很多企业面临估值下跌,资金吃紧,用户流失的关键节点,怎样从零售经营的......一起来看看 《走出电商困局》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

html转js在线工具
html转js在线工具

html转js在线工具