c++ - Mac GUI 应用程序如何在不使用 Sparkle 的情况下自行重新启动?

标签 c++ objective-c c macos relaunch

我正在向 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/

相关文章:

c++ - 如何突出显示 QTextEdit 中的文本字符串

c++ - 分配的内存被回收

ios - 为什么 AFNetworking 的 JSON 请求失败?

c - open(O_CREATE) 权限的八进制字符串到整数

c++ - 消除 HTML 的最佳 C/C++ 库?

c++ - 用 C++ 存储大矩阵 (Armadillo)

c++ - 是否/arch :AVX enable AVX2?

ios - 使用 afnetworking 的互联网连接可达性

objective-c - IOS:停止 UIAlert 循环

c - 如何检测\n然后删除它?