zoukankan      html  css  js  c++  java
  • Objective-C MacOS以管理员权限执行程序

    在MacOS下非常多操作是须要管理员权限的, 比方我们执行chmod。在命令行下能够使用sudo chmod来申请以管理员权限执行。可是使用XCode写的程序是不能使用sudo的。

    须要自己写代码来申请权限。以下是一个样例。 以管理员身份执行chmod 777

    bool ChmodFileWithElevatedPrivilegesFromLocation(NSString *location)
    {
        // Create authorization reference
        OSStatus status;
        AuthorizationRef authorizationRef;
    
        status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authorizationRef);
        if (status != errAuthorizationSuccess)
        {
            NSLog(@"Error Creating Initial Authorization: %d", status);
            return NO;
        }
    
        AuthorizationItem right = {kAuthorizationRightExecute, 0, NULL, 0};
        AuthorizationRights rights = {1, &right};
        AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed |
        kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights;
      
        status = AuthorizationCopyRights(authorizationRef, &rights, NULL, flags, NULL);
        if (status != errAuthorizationSuccess)
        {
            NSLog(@"Copy Rights Unsuccessful: %d", status);
            return NO;
        }
        
        // use chmod
        char *tool = "/bin/chmod";
        char *args[] = {"777", (char *)[location UTF8String], NULL};
        FILE *pipe = NULL;
        status = AuthorizationExecuteWithPrivileges(authorizationRef, tool, kAuthorizationFlagDefaults, args, &pipe);
        if (status != errAuthorizationSuccess)
        {
            NSLog(@"Error: %d", status);
            return NO;
        }
        
        status = AuthorizationFree(authorizationRef, kAuthorizationFlagDestroyRights);
        return YES;
    }
    

    调用方法

    bool bRet = ChmodFileWithElevatedPrivilegesFromLocation("/Library");
    if(bRet)
    {
        NSLog(@"error");
    }
    else
    {
        NSLog(@"sucess");
    }


  • 相关阅读:
    (十三)过滤器Filter(转)
    (十二)会话跟踪技术之servlet通信(forward和include)
    (十一)会话跟踪技术之作用域(request、session、servletContext)
    openjdk源码目录结构
    java socket相关的timeout
    eclipse创建maven web app
    hadoop mapred和mapreduce包
    hadoop shuffle
    bash shell和进程
    bash shell中的特殊用法
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/7402813.html
Copyright © 2011-2022 走看看