美文网首页
OC 切换到用户态执行命令sudo su

OC 切换到用户态执行命令sudo su

作者: 皮蛋豆腐酱油 | 来源:发表于2019-08-07 14:01 被阅读0次
//xcode9需要额外import这个,不然SCDynamicStoreCopyConsoleUser这个方法找不到
#import <SystemConfiguration/SystemConfiguration.h>
- (NSString *)getCurrentUserName
{
    uid_t uid = 0;
    gid_t gid = 0;
    CFStringRef cfsUsrName = SCDynamicStoreCopyConsoleUser(NULL, &uid, &gid);
    if (cfsUsrName == NULL) {
        return @"";
    }
    
    NSString *userName = [NSString stringWithString:(__bridge NSString *)cfsUsrName];
    CFRelease(cfsUsrName);
    
    return userName;
}

- (BOOL)exec {
    //获取用户名
    NSString *userName = [self getCurrentUserName];
    if (!userName || userName.length == 0) {
        return NO;
    }

    NSString *str = @"defaults -currentHost write com.apple.screensaver idleTime 600";//这个是一个改屏保时间的命令
    NSString *command = [NSString stringWithFormat:@"su - %@ -c \"%@\"", userName, str];
    NSArray *arguments = [NSArray arrayWithObjects:@"-c", command, nil];
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/sh"];
    [task setArguments:arguments];
    [task launch];
    [task waitUntilExit];//有了这行,就变成了同步的,没有就是异步的
    int st = [task terminationStatus];
    if (st == 0) {
      return YES;
    } else {
      return NO;
    }
}

相关文章

网友评论

      本文标题:OC 切换到用户态执行命令sudo su

      本文链接:https://www.haomeiwen.com/subject/lwnidctx.html