码迷,mamicode.com
首页 > 系统相关 > 详细

Objective-C MacOS以管理员权限运行程序

时间:2015-07-10 20:55:11      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:xcode   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");
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

Objective-C MacOS以管理员权限运行程序

标签:xcode   objective-c   macos   

原文地址:http://blog.csdn.net/sysprogram/article/details/46834087

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!