Search code examples
objective-cmacosdaemonlaunchd

Daemon isn't loaded with SMJobSubmit objective C


I want to write a program which load a daemon with SMJobSubmit() API Here's my code :

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;
}

But it gives this error :

SMJobSubmit[822:707] Authenticated install submit failed with error Error Domain=kSMErrorDomainFramework Code=2051 "The operation couldn’t be completed. (kSMErrorDomainFramework error 2051 - The job specified to load into launchd was not valid.)" UserInfo=0x100115750 {NSDescription=The job specified to load into launchd was not valid.}

What is the problem ? Thanks in advance !


Solution

  • ProgramArguments shouldn't be empty. The first element of the ProgramArguments array should be the same as the Program key. See the launchd documentation and execvp man page for more details.