从 nstask 获取数据 - 与命令行通信 - 目标 c [英] Getting data from the nstask - communicating with command line - objective c

查看:49
本文介绍了从 nstask 获取数据 - 与命令行通信 - 目标 c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何向任务发送数据:

I know how to send data to the task:

NSData *charlieSendData = [[charlieImputText stringValue] dataUsingEncoding:NSUTF8StringEncoding];
[[[task standardInput] fileHandleForWriting] writeData:charlieSendData];

但是我如何得到任务的响应??

But how do I get what the task responds with??

以利亚

推荐答案

给出一个 NSPipe 或一个 NSFileHandle 作为任务的 standardOutput,以及从中阅读.

Give an NSPipe or an NSFileHandle as the task's standardOutput, and read from that.

NSTask * list = [[NSTask alloc] init];
[list setLaunchPath:@"/bin/ls"];
[list setCurrentDirectoryPath:@"/"];

NSPipe * out = [NSPipe pipe];
[list setStandardOutput:out];

[list launch];
[list waitUntilExit];
[list release];

NSFileHandle * read = [out fileHandleForReading];
NSData * dataRead = [read readDataToEndOfFile];
NSString * stringRead = [[[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"output: %@", stringRead);

请注意,如果您使用管道,则必须担心管道会被填满.如果您提供一个 NSFileHandle 代替,任务可以输出它想要的所有内容,而不必担心丢失任何内容,但您也会获得必须将数据写入磁盘的开销.

Note that if you use a pipe, you have to worry about the pipe filling up. If you provide an NSFileHandle instead, the task can output all it wants without you having to worry about losing any, but you also get the overhead of having to write the data out to disk.

这篇关于从 nstask 获取数据 - 与命令行通信 - 目标 c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆