gpt4 book ai didi

objective-c - 从 root 帐户启动应用程序

转载 作者:搜寻专家 更新时间:2023-10-30 20:01:36 24 4
gpt4 key购买 nike

我正在开发具有 Objective-C 守护程序的 Cocoa GUI 应用程序。守护进程由 LaunchDaemon 启动,GUI 使用每个用户的 loginItems 启动。

部署更新时,我需要更新守护进程,这很简单,并更新 GUI。我希望能够退出 GUI,替换应用程序,然后在当前运行它的每个用户帐户上重新启动它。我想从当然以 root 身份运行的守护进程中执行所有这些操作。

我怎样才能:1) 作为 root,退出然后在另一个用户界面中重新启动应用程序?2) 以 root 身份退出,然后为当前登录的每个用户重新启动特定的 loginItem?

我已经尝试搜索并且有很多讨论包括这个 similar question ,但似乎没有可用的工作解决方案。

非常感谢任何帮助。

最佳答案

我相信 NSDistributedNotificationCenter 应该为此工作。请注意,使用 NSDistributedNotificationCenter 在不同用户帐户中的进程之间进行通信本身并不需要 root 权限。

为了帮助协调用户帐户,它可能有助于区分 GUI 应用程序和守护程序的哪些实例当前处于事件状态并受控制,哪些实例是被动的。您可以使用 NSWorkspace 的通知(NSWorkspaceSessionDidBecomeActiveNotification、NSWorkspaceSessionDidResignActiveNotification)来确定用户何时在用户帐户等之间切换,并相应地设置您的实例。

假设您的 GUI 应用程序和守护程序在 3 个不同的用户帐户中运行实例。例如,如果在事件用户帐户中,你想开始更新过程,你可以使用 NSDistributedNotificationCenter 轻松地告诉所有其他实例立即关闭。为此,您需要定义如下内容。

在 .h 文件中,声明不同通知的名称:

extern NSString * const MDShouldTerminateImmediatelyNotification;

在(一个)实现文件中,创建名称,并将类设置为对该名称的分布式通知感兴趣,等等:

NSString * const MDShouldTerminateImmediatelyNotification = @"MDShouldTerminateImmediately";


- (id)init {
if (self = [super init]) {
[[NSDistributedNotificationCenter defaultCenter]
addObserver:self
selector:@selector(shouldTerminateImmediately:)
name:MDShouldTerminateImmediatelyNotification
object:nil];
}
return self;
}

- (void)dealloc {
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}

- (void)shouldTerminateImmediately:(NSNotification *)notification {
if (ourInstanceIsInControl == NO) {
[NSApp terminate:nil];
}
}

在将启动更新过程的类中,您将执行如下操作来发送通知:

- (void)beginUpdate {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:MDShouldTerminateImmediatelyNotification
object:[self description] // or just nil
userInfo:nil
options:NSNotificationDeliverImmediately | NSNotificationPostToAllSessions];
// continue

}

这至少应该是一个开始,我想......

实际上,如果您谈论的是让一个单一的守护进程实例以根用户身份运行并在所有用户帐户中执行所有操作,您可能需要考虑将该部分分解为 Launchd Agent 类型的进程(后台进程,在用户级别运行,每个用户帐户都有自己的实例)。

更多信息:

Technical Note TN2083 Daemons and Agents

Root and Login Sessions

Creating launchd Daemons and Agents

关于objective-c - 从 root 帐户启动应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4319210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com