使用NSTask启动命令会返回错误

时间:2014-06-10 09:41:55

标签: objective-c daemon nstask start-stop-daemon

我想使用NSTask从我的应用程序启动以下命令:

  

sudo -u myusername launchctl load /Library/LaunchAgents/com.google.keystone.agent.plist

这是我做的代码:     NSPipe * pipe = [NSPipe pipe];

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
[task setCurrentDirectoryPath:@"/"];
[task setStandardError:pipe];

NSArray *arguments = nil;
arguments = @[@"sudo",
              @"-u",
              @"myusername",
              @"launchctl",
              @"load",
              @"/Library/LaunchAgents/com.google.keystone.agent.plist"];

[task setArguments: arguments];

NSFileHandle * read = [pipe fileHandleForReading];

[task launch];
[task waitUntilExit];

NSData * dataRead = [read readDataToEndOfFile];
NSString * output = [[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding];
NSLog(@"output: %@", output);

处理完后,我收到以下错误:

  

/ bin / sh:sudo:没有这样的文件或目录

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:

arguments = @[@"-c",
              @"sudo -u myusername launchctl load /Library/LaunchAgents/com.google.keystone.agent.plist"];