我试图在我的OS X应用程序中以编程方式运行sudo命令,
但我收到了这些消息
sudo:没有tty存在且没有指定askpass程序
这是我的代码:
NSString *runCommand(NSString *commandToRun)
{
NSTask *task;
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;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *output;
output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
return output;
}
我称这种方法是这样的:
runCommand(@"sudo purge");
感谢您提供任何帮助或宣传。