你可以用100
.下面是一个运行"/usr/bin/grep foo bar.txt
"的示例.
int pid = [[NSProcessInfo processInfo] processIdentifier];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/grep";
task.arguments = @[@"foo", @"bar.txt"];
task.standardOutput = pipe;
[task launch];
NSData *data = [file readDataToEndOfFile];
[file closeFile];
NSString *grepOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"grep returned:\n%@", grepOutput);
NSPipe
和NSFileHandle
用于重定向任务的标准输出.
有关在Objective-C应用程序中与操作系统交互的更多详细信息,请参阅苹果开发中心的以下文档:Interacting with the Operating System.
编辑:包括NSLog问题的修复
如果您正在使用NSTask通过bash运行命令行实用程序,那么您需要包含以下魔行以保持NSLog正常工作:
//The magic line that keeps your log where it belongs
task.standardOutput = pipe;
这里有一个解释:https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask