在MacOS下很多操作是需要管理员权限的, 比如我们运行chmod,在命令行下可以使用sudo chmod来申请以管理员权限运行。但是使用XCode写的程序是不能使用sudo的。
需要自己写代码来申请权限。下面是一个例子,以管理员身份运行chmod 777。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
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 charchar *tool = "/bin/chmod"; charchar *args[] = {"777", (charchar *)[location UTF8String], NULL}; FILEFILE *pipe = NULL; status = AuthorizationExecuteWithPrivileges(authorizationRef, tool, kAuthorizationFlagDefaults, args, &pipe); if (status != errAuthorizationSuccess) { NSLog(@"Error: %d", status); return NO; } status = AuthorizationFree(authorizationRef, kAuthorizationFlagDestroyRights); return YES; } |
调用方法
1 2 3 4 5 6 7 8 9 |
bool bRet = ChmodFileWithElevatedPrivilegesFromLocation("/Library"); if(bRet) { NSLog(@"error"); } else { NSLog(@"sucess"); } |