【问题标题】:Issue getting NSTask and SMJobSubmit to run properly问题让 NSTask 和 SMJobSubmit 正常运行
【发布时间】:2014-08-04 15:32:13
【问题描述】:

据我所知,这段代码应该以提升的权限运行我的脚本,但 NSTask 似乎并没有真正启动。我对 Objective-C 和 Cocoa 比较陌生,所以我可能在这里遗漏了一些简单的东西,但无论哪种方式,我都不知道为什么这不起作用。

CFErrorRef error;
AuthorizationItem authItem = { kSMRightBlessPrivilegedHelper, 0, NULL, 0 };
AuthorizationRights authRights = { 1, &authItem };
AuthorizationFlags flags = kAuthorizationFlagInteractionAllowed | kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights;
AuthorizationRef auth;

if(AuthorizationCreate(&authRights, kAuthorizationEmptyEnvironment, flags, &auth) == errAuthorizationSuccess)
{
    NSString* myLabel = @"com.hidden.backup";
    (void) SMJobRemove( kSMDomainSystemLaunchd, (__bridge CFStringRef)myLabel, auth, false, NULL );

    NSString *path = [[NSBundle mainBundle] pathForResource:@"kandorBackup" ofType:@"sh"];
    NSPipe *outputPipe = [NSPipe pipe];
    readHandle = [outputPipe fileHandleForReading];
    inData = nil;
    returnValue = nil;

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:path];
    [task setArguments:[NSArray arrayWithObjects:login, selectedDrive, rsyncFinalFlags, nil]];
    [task setStandardOutput:outputPipe];
    [readHandle waitForDataInBackgroundAndNotify];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(recievedData:)
                                                 name:NSFileHandleDataAvailableNotification
                                               object:nil];

    SMJobSubmit( kSMDomainSystemLaunchd, (__bridge CFDictionaryRef)task, auth, &error);
}

如果有帮助,我会在 Xcode 调试区域收到这两个错误:

2014-08-04 11:44:39.169 <hidden>[68065:303] -[NSConcreteTask objectForKey:]: unrecognized selector sent to instance 0x600000099d70
2014-08-04 11:44:39.169 <hidden>[68065:303] Exception detected while handling key input.

【问题讨论】:

    标签: cocoa nstask


    【解决方案1】:

    SMJobSubmit 不用于提升 NSTask。您宁愿构造一个与 LaunchDaemon/LaunchAgent plist 文件格式相同的 NSDictionary,并将该 NSDictionary 传递给 SMJobSubmit。

    你会这样做

    NSDictionary *dictionary = @{@"ProgramArguments": @[path,login, selectedDrive, rsyncFinalFlags]};
    SMJobSubmit( kSMDomainSystemLaunchd, (__bridge CFDictionaryRef)dictionary, auth, &error);
    

    不幸的是,您将不会收到任何进度消息,如果这是必要的,您将需要构建一个特权帮助工具并从那里执行 NSTask。

    https://developer.apple.com/library/mac/samplecode/EvenBetterAuthorizationSample/Listings/Read_Me_About_EvenBetterAuthorizationSample_txt.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 2018-07-07
      • 2012-04-13
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      相关资源
      最近更新 更多