如果不使用Sparkle,Mac GUI应用程序如何重新启动?

Bob*_*phy 2 c c++ macos objective-c relaunch

我正在为Mac程序添加一项功能,以删除其首选项.plist文件,然后重新启动有效的"出厂设置".但是,客户对于使用Sparkle等外部框架持谨慎态度.我在网上查看了示例代码,但其中大部分内容似乎过于复杂(例如,向NSApplication添加一个类别).此外,当您无法使用某些API从非GUI进程启动GUI进程时,其中一些将无法在Lion或更高版本中运行.

那么有一个简单的方法让Mac GUI应用程序重新启动吗?

Bob*_*phy 9

至少对于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);
}
Run Code Online (Sandbox Code Playgroud)

我遇到了一个陷阱,这是重新启动的应用程序可以在后台结束.在执行早期执行此操作可修复该问题:

[[NSApplication sharedApplication] activateIgnoringOtherApps : YES];
Run Code Online (Sandbox Code Playgroud)

  • 调用`fork()`有什么意义呢?为什么不直接调用`execl()`? (2认同)