我正在向 Mac 程序添加一项功能,以删除其首选项 .plist 文件,然后使用有效的“出厂设置”重新启动。然而,客户对此持怀疑态度,不愿使用 Sparkle 等外部框架。我在网上查找示例代码,但其中大部分似乎过于复杂(例如,向 NSApplication 添加类别)。此外,当您无法使用某些 API 从非 GUI 进程启动 GUI 进程时,其中一些在 Lion 或更高版本中根本不起作用。
那么有没有一种简单的方法可以让 Mac GUI 应用程序自行重新启动?
最佳答案
至少对于 Mountain Lion 来说,稍微花哨的 fork/exec 版本可以正常工作:
void RelaunchCurrentApp()
{
// Get the path to the current running app executable
NSBundle* mainBundle = [NSBundle mainBundle];
NSString* executablePath = [mainBundle executablePath];
const char* execPtr = [executablePath UTF8String];
#if ATEXIT_HANDLING_NEEDED
// Get the pid of the parent process
pid_t originalParentPid = getpid();
// Fork a child process
pid_t pid = fork();
if (pid != 0) // Parent process - exit so atexit() is called
{
exit(0);
}
// Now in the child process
// Wait for the parent to die. When it does, the parent pid changes.
while (getppid() == originalParentPid)
{
usleep(250 * 1000); // Wait .25 second
}
#endif
// Do the relaunch
execl(execPtr, execPtr, NULL);
}
我遇到了一个问题,那就是重新启动的应用程序可能会在后台结束。在执行的早期这样做可以解决这个问题:
[[NSApplication sharedApplication] activateIgnoringOtherApps : YES];
关于c++ - Mac GUI 应用程序如何在不使用 Sparkle 的情况下自行重新启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15305845/