守护程序未加载SMJobSubmit目标C.

时间:2013-04-15 07:23:17

标签: objective-c macos daemon launchd

我想编写一个用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]经过身份验证的安装提交失败,错误错误Domain = kSMErrorDomainFramework Code = 2051“操作无法完成。(kSMErrorDomainFramework错误2051 - 指定加载到launchd的作业无效。)”UserInfo = 0x100115750 {NSDescription =指定加载到launchd的作业无效。}

有什么问题? 提前谢谢!

1 个答案:

答案 0 :(得分:1)

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