3

在 OS X 中,我如何在下载更新版本后自动重新启动我的应用程序?

我环顾四周,launchd 似乎是这样做的可能方法,但我似乎无法理解它。我似乎也找不到任何专门谈论这个的好资源。

我也可以创建一个脚本或单独的进程来执行此操作,但这似乎很笨拙,我期待那里有更好的解决方案。

4

3 回答 3

3

单独的过程是很好的解决方案,看看 Sparkle 框架(大多数应用程序使用它来自动更新),他们也用于这个独立的应用程序 - https://github.com/andymatuschak/Sparkle/blob/master/relaunch.m

于 2010-11-24T21:15:52.247 回答
2

只是扩展了 Julia 的回答,因为我不得不重新启动我的应用程序而不是更新,所以我研究了 Sparkle 是如何做到的 -

Sparkle 的最新版本(截至 11/2011)有一个名为 finish_installation.app 的项目目标,它包含在 Sparkle 框架的 Resources 目录中。Sparkle 作为宿主 App 的一部分运行,将 finish_application 复制到 application_support 目录并使用 launch 来运行其二进制可执行文件,如下所示,传入宿主进程 ID 和重新启动路径:

NSString *relaunchToolPath = [NSString stringWithFormat:@"%@/finish_installation.app/Contents/MacOS/finish_installation", tempDir];
[NSTask launchedTaskWithLaunchPath: relaunchToolPath arguments:[NSArray arrayWithObjects:pathToRelaunch, [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], tempDir, relaunch ? @"1" : @"0", nil]];
[NSApp terminate:self];

似乎使用这个函数,当父进程退出时(?),finish_application 的父进程被启动。

finish_installation 等待传入的进程 id 消失,还有一个初始检查以查看它的父进程是否已启动 (pid=1)

if(getppid() == 1)...
if (GetProcessForPID(parentprocessid, &psn) == procNotFound)...

然后启动应用程序:

[[NSWorkspace sharedWorkspace] openFile: appPath];

最后一个有趣的花絮:如果安装需要很长时间,finish_installation 会将自身更改为前台进程,以便用户可以看到某个应用程序正在运行:

ProcessSerialNumber     psn = { 0, kCurrentProcess };
TransformProcessType( &psn, kProcessTransformToForegroundApplication );
于 2011-11-03T19:10:04.093 回答
1

源博客

- (void) restartOurselves
    {
       //$N = argv[N]
       NSString *killArg1AndOpenArg2Script = @"kill -9 $1 \n open \"$2\"";

       //NSTask needs its arguments to be strings
       NSString *ourPID = [NSString stringWithFormat:@"%d",
                      [[NSProcessInfo processInfo] processIdentifier]];

       //this will be the path to the .app bundle,
       //not the executable inside it; exactly what `open` wants
       NSString * pathToUs = [[NSBundle mainBundle] bundlePath];

       NSArray *shArgs = [NSArray arrayWithObjects:@"-c", // -c tells sh to execute the next argument, passing it the remaining arguments.
                    killArg1AndOpenArg2Script,
                    @"", //$0 path to script (ignored)
                    ourPID, //$1 in restartScript
                    pathToUs, //$2 in the restartScript
                    nil];
       NSTask *restartTask = [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:shArgs];
       [restartTask waitUntilExit]; //wait for killArg1AndOpenArg2Script to finish
       NSLog(@"*** ERROR: %@ should have been terminated, but we are still running", pathToUs);
       assert(!"We should not be running!");
    }
于 2018-07-10T15:15:32.607 回答