加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 在OS X中使用NSTask在特定用户下运行“launchctl

发布时间:2020-12-16 07:09:01 所属栏目:百科 来源:网络整理
导读:我的应用程序是在root下启动的,我需要能够使用NSTask和launchctl卸载进程 这是我做的代码: NSPipe *pipe = [NSPipe pipe]; NSTask *task = [[NSTask alloc] init]; [task setLaunchPath: @"/bin/launchctl"]; [task setCurrentDirectoryPath:@"/"]; [task s
我的应用程序是在root下启动的,我需要能够使用NSTask和launchctl卸载进程
这是我做的代码:

NSPipe *pipe = [NSPipe pipe];

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/launchctl"];
    [task setCurrentDirectoryPath:@"/"];
    [task setStandardError:pipe];

    NSLog(@"/bin/launchctl unload %@",plistAutostartLocation);

    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: enableCommand,plistAutostartLocation,nil];
    [task setArguments: arguments];

    NSFileHandle * read = [pipe fileHandleForReading];

    [task launch];
    [task waitUntilExit];

如果需要卸载的进程在“root”下启动,那么如果失败则成功卸载.
问题是如何在特定用户(例如“myusername”)下运行“launchctl”?

编辑:
在终端,如果我想在特定用户下运行一些命令,我??接下来做的很好:

su – myusername -c “ls /Users/myusername”

但是当我尝试在特定用户下运行“launchctl”时,它失败了:

su – myusername -c “launchctl load /Library/LaunchAgents/com.google.keystone.agent.plist”

它说:“没有发现任何东西加载”

解决方法

您的上一个命令失败与引导名称空间有关,您试图在错误的引导程序命名空间中加载代理程序.系统正在创建两个不同的引导名称空间,摘录自 Apple documentation:

It’s worth noting the distinction between GUI and non-GUI per-session
bootstrap namespaces
. A GUI per-session bootstrap namespace is
instantiated by the GUI infrastructure (loginwindow and WindowServer)
when a user logs in via the GUI. A non-GUI per-session bootstrap
namespace is created when a user logs in via SSH. While there is no
fundamental difference between these namespaces,GUI-based services,
like the Dock,only register themselves in GUI per-session bootstrap
namespaces.

su命令不是在launchd使用的同一个bootsrap命名空间中启动的.

有两种方法可以运行您想要在正确的引导程序命名空间中运行的命令:

> 10.10及以上:使用launchctl asuser.这将运行由指定的< myusername>启动的任何命令.值得一提的是,您必须以root身份运行它,否则命令将失败.您的上一个命令应该像这样运行:

launchctl asuser <myusername> launchctl load "/Library/LaunchAgents/com.google.keystone.agent.plist"

> 10.10及以下(自10.11起,SIP阻止此方法):使用launchctl bsexec.这需要一个进程id来检索正确的命名空间,在该命名空间中运行另一个命令.此外,您必须手动更改命令的UID,如下所示:

launctl bsexec <pid> su -u <myusername> launchctl load "/Library/LaunchAgents/com.google.keystone.agent.plist"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读