NSTask方法
简单使用
- (void)run:(NSString *)cmd{
[[NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:@[@"-c",cmd]]waitUntilExit];
}
异步多线程使用
此方法目的是为了解决执行命令期间阻塞主线程的问题
+ (void)runShellWithCommand:(NSString *)command completeBlock:(dispatch_block_t)completeBlock{
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY,0), ^{
NSTask *task = [[NSTask alloc]init];
[task setLaunchPath:@"/bin/sh"];
NSArray *arguments;
arguments = [NSArray arrayWithObjects:@"-c" ,command,nil];
[task setArguments:arguments];
[task launch];
[task waitUntilExit];
dispatch_async(dispatch_get_main_queue(), ^{
if(completeBlock){
completeBlock();
}
});
});
}
pipe方法
- (NSString *)excuteCommand:(NSString *)cmd{
NSString *output = [NSString string];
FILE *pipe = popen([cmd cStringUsingEncoding:NSASCIIStringEncoding],"r+");
if (!pipe){
return @"";
}
char buf[102400];
while(fgets(buf,sizeof(buf),pipe)!=NULL){
output = [output stringByAppendingFormat:@"%s",buf];
}
pclose(pipe);
_Log.string = [_Log.string stringByAppendingString:[NSString stringWithFormat:@"%@\n",output]];
return output;
}
system方法
system(cmd);