简体   繁体   中英

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.

你可以使用applescript

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

From C you can use the SMJobRemove function. If the job is in the system launchd context (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM