从Cocoa应用程序执行终端命令如何执行终端命令(如grep)从我的目标-C可可申请?
3 回答
万千封印
TA贡献1891条经验 获得超3个赞
这个runCommand方法不需要脚本文件,只需运行一个命令行:
- (NSString *)runCommand:(NSString *)commandToRun{ NSTask *task = [[NSTask alloc] init]; [task setLaunchPath:@"/bin/sh"]; NSArray *arguments = [NSArray arrayWithObjects: @"-c" , [NSString stringWithFormat:@"%@", commandToRun], nil]; NSLog(@"run command:%@", commandToRun); [task setArguments:arguments]; NSPipe *pipe = [NSPipe pipe]; [task setStandardOutput:pipe]; NSFileHandle *file = [pipe fileHandleForReading]; [task launch]; NSData *data = [file readDataToEndOfFile]; NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return output;}
您可以这样使用这个方法:
NSString *output = runCommand(@"ps -A | grep mysql");
- 3 回答
- 0 关注
- 890 浏览
添加回答
举报
0/150
提交
取消