What is the proper way to run something like $sudo touch folder_name
or $sudo rm
from within Objective-C/Cocoa? I'm changing and moving开发者_高级运维 around a few files and need elevated privileges. Any code sample would be greatly appreciated. Thanks.
One way to do it is AuthorizationExecuteWithPrivileges()
, but that's discouraged for the normal course of things. Mainly it's for installers, I gather.
Something like:
AuthorizationRef auth = NULL;
OSStatus err = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagInteractionAllowed, &auth);
err = AuthorizationExecuteWithPrivileges(auth, command, kAuthorizationFlagDefaults, args, NULL);
And you add appropriate checking of err
...
See the Authorization documentation.
There are several ways to do this. Which one you choose depends on what you want to do. The simplest and unsafest way is to simple set the s-bit on an extra helper tool that you call from your code and does what needs admin rights. Take a look at the BetterAuthorizationSample for the most fancy and complicated way of executing privileged code.
The Authorization Services Programming Guide gives you all you need.
精彩评论