我想从目标 C(Cocoa 框架)执行命令。我正在尝试的命令如下。我尝试使用 NSTask,但是当我执行它时它说“启动路径不可访问”。
sudo ifconfig en0 down
我的代码是:
- (void)testme {
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"sudo ifconfig en0 down"];
NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"foo", @"bar.txt", nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"command returned:\n%@", string);
[string release];
[task release];
}