0

我想编写一个使用 SMJobSubmit() API 加载守护进程的程序,这是我的代码:

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString* myLabel = @"com.apple.mydaemon";

    AuthorizationItem authItem = { kSMRightBlessPrivilegedHelper, 0, NULL, 0 };
    AuthorizationRights authRights = { 1, &authItem };
    AuthorizationFlags flags = kAuthorizationFlagInteractionAllowed | kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights;
    NSString *executablePath=@"/usr/libexec/mydaemon";
    AuthorizationRef auth;
    CFErrorRef error=0;
    if( AuthorizationCreate( &authRights, kAuthorizationEmptyEnvironment, flags, &auth ) == errAuthorizationSuccess ) {
        (void) SMJobRemove( kSMDomainSystemLaunchd, (CFStringRef)myLabel, auth, false, NULL );
        //NSLog( @"Authenticated install submit failed with error %@", error );

        NSMutableDictionary *plist = [NSMutableDictionary dictionary];
        NSMutableDictionary * programArgumnets=[NSMutableDictionary new];
        [programArgumnets setObject:executablePath forKey:@"item0"];
        [plist setObject:myLabel forKey:@"Label"];
        [plist setObject:programArgumnets forKey:@"ProgramArguments"];
        [plist setObject:[NSNumber numberWithBool:YES] forKey:@"RunAtLoad"];
        [plist setObject:[NSNumber numberWithBool:YES] forKey:@"KeepAlive"];

        if ( SMJobSubmit( kSMDomainUserLaunchd, (CFDictionaryRef)plist, auth, &error) ) {
            // Script is running
        } else {
            NSLog( @"Authenticated install submit failed with error %@", error );
        }
        if ( error ) {
            CFRelease( error );
        }

            (void) SMJobRemove( kSMDomainSystemLaunchd, (CFStringRef)myLabel, auth, false, NULL );
        AuthorizationFree( auth, 0 );
    }

    [pool drain];
    return 0;
}

但它给出了这个错误:

SMJobSubmit[822:707] 验证安装提交失败,错误域=kSMErrorDomainFramework Code=2051“操作无法完成。(kSMErrorDomainFramework 错误 2051 - 指定加载到 launchd 的作业无效。)” UserInfo=0x100115750 { NSDescription=指定加载到 launchd 的作业无效。}

问题是什么 ?提前致谢 !

4

1 回答 1

1

ProgramArguments 不应为空。ProgramArguments 数组的第一个元素应与 Program 键相同。有关更多详细信息,请参阅 launchd 文档和 execvp 手册页。

于 2013-04-17T23:57:09.543 回答