在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"); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/sysprogram/article/details/46834087