Execute a terminal command from a Cocoa app

后端 未结 12 2375
既然无缘
既然无缘 2020-11-22 06:34

How can I execute a terminal command (like grep) from my Objective-C Cocoa application?

12条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 07:05

    If the Terminal command requires Administrator Privilege (aka sudo), use AuthorizationExecuteWithPrivileges instead. The following will create a file named "com.stackoverflow.test" is the root directory "/System/Library/Caches".

    AuthorizationRef authorizationRef;
    FILE *pipe = NULL;
    OSStatus err = AuthorizationCreate(nil,
                                       kAuthorizationEmptyEnvironment,
                                       kAuthorizationFlagDefaults,
                                       &authorizationRef);
    
    char *command= "/usr/bin/touch";
    char *args[] = {"/System/Library/Caches/com.stackoverflow.test", nil};
    
    err = AuthorizationExecuteWithPrivileges(authorizationRef,
                                             command,
                                             kAuthorizationFlagDefaults,
                                             args,
                                             &pipe); 
    

提交回复
热议问题