ytw
ytw

Reputation: 1355

Mac OS X: In Objective-C or C, how to unload (stop) a LaunchDaemon managed by launched

I would like to know how to write Objective-C or C code to unload (stop) a LaunchDaemon. The LaunchDaemon that I want to unload is running as root user.

My question is basically the same as this one: How to Load LaunchDaemon plist from my Mac Application. The only difference is that he/she is trying to load, but I want to unload.

Upvotes: 1

Views: 1145

Answers (2)

user23743
user23743

Reputation:

From C you can use the SMJobRemove function. If the job is in the system launchd context (i.e. it's in /Library/LaunchDaemons and is loaded—if not launched—at system startup) then you'll need to use Authorization Services to acquire the kSMRightModifySystemDaemons right, and pass the authorization reference to this function.

    AuthorizationItem authItem = { .name = kSMRightModifySystemDaemons,
        .valueLength = 0,
        .value = NULL,
        .flags = kAuthorizationFlagDefaults };
    AuthorizationRights authRights  = { .count = 1,
        .items = &authItem };

    AuthorizationRef authorization = NULL;
    OSStatus authResult = AuthorizationCreate(&authRights,
                                          kAuthorizationEmptyEnvironment,
                                          kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights,
                                          &authorization);
    if (authResult != errAuthorizationSuccess) {
        NSLog(@"couldn't create AuthorizationRef: error %i", authResult);
    } else {
        CFErrorRef error = NULL;
        BOOL removeResult = SMJobRemove(kSMDomainSystemLaunchd, jobLabel, authorization, waitOrNot, &error);
        AuthorizationFree(authorization, kAuthorizationFlagDefaults);
        // handle either success or failure
    }

The waitOrNot flag should be set to YES if you want to block until the job has been unloaded—this could potentially take a long time.

Upvotes: 2

Parag Bafna
Parag Bafna

Reputation: 22930

You can use applescript

do shell script "launchctl unload /Library/LaunchDaemons/com.yourcompany.app.plist" with administrator privileges

Upvotes: 2

Related Questions