gpt4 book ai didi

macos - NSTask的实时输出

转载 作者:行者123 更新时间:2023-12-01 18:30:18 26 4
gpt4 key购买 nike

我有一个 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);
}
}

关于macos - NSTask的实时输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6931732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com