
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应用程序中与 *** 作系统交互的更多详细信息,您可以在Apple的开发中心:Interacting with the Operating System上查看此文档。
编辑:包括NSLog问题的修复
如果你使用NSTask通过bash运行命令行实用程序,那么你需要包括这条魔法线以保持NSLog工作:
//The magic line that keeps your log where it belongstask.standardOutput = pipe;
解释在这里:http://cocoadev.com/HowToPipeCommandsWithNSTask(< – 死链接)
总结以上是内存溢出为你收集整理的objective-c – 从Cocoa应用程序执行终端命令全部内容,希望文章能够帮你解决objective-c – 从Cocoa应用程序执行终端命令所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)