gpt4 book ai didi

objective-c - 重新启动 cocoa 应用程序

转载 作者:太空狗 更新时间:2023-10-30 03:47:55 27 4
gpt4 key购买 nike

我有一个应用程序检查其命令行参数并将值存储在持久存储中。其中之一是我不想让人们通过“ps”和 friend 看到的密码。我目前正在研究的方法是,在我存储了我需要的值之后,在没有命令行参数的情况下重新启动进程。我天真的方法是这样的,其中 args[0] 是应用程序的路径:

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:[args objectAtIndex:0]];
[task launch];
[task release];
[NSApp terminate:nil];

child 跑了。但是,当我的应用程序终止时, child 似乎并没有成为孤儿,而是被卡住了。我离这个还远吗?

更多信息:所以当我调用 [NSApp terminate:nil] 时,启动的 NSTask 似乎卡住了,但如果我只是 exit() 那么它工作正常。但是,我担心如果我这样做,打开的东西(钥匙串(keychain)、plist 等)将处于糟糕状态。

请注意,许多示例代码都是关于一些类似看门狗的进程,在需要时重新启动一个单独的进程。我正在尝试重新启动已在同一进程中运行的当前进程。

最佳答案

网上有很多例子,但是this one (也在下面)看起来它有你需要的所有代码。有more detailed explanations也在那里。

// gcc -Wall -arch i386 -arch ppc -mmacosx-version-min=10.4 -Os -framework AppKit -o relaunch relaunch.m

#import <AppKit/AppKit.h>

@interface TerminationListener : NSObject
{
const char *executablePath;
pid_t parentProcessId;
}

- (void) relaunch;

@end

@implementation TerminationListener

- (id) initWithExecutablePath:(const char *)execPath parentProcessId:(pid_t)ppid
{
self = [super init];
if (self != nil) {
executablePath = execPath;
parentProcessId = ppid;

// This adds the input source required by the run loop
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationDidTerminate:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
if (getppid() == 1) {
// ppid is launchd (1) => parent terminated already
[self relaunch];
}
}
return self;
}

- (void) applicationDidTerminate:(NSNotification *)notification
{
if (parentProcessId == [[[notification userInfo] valueForKey:@"NSApplicationProcessIdentifier"] intValue]) {
// parent just terminated
[self relaunch];
}
}

- (void) relaunch
{
[[NSWorkspace sharedWorkspace] launchApplication:[NSString stringWithUTF8String:executablePath]];
exit(0);
}

@end

int main (int argc, const char * argv[])
{
if (argc != 3) return EXIT_FAILURE;

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

[[[TerminationListener alloc] initWithExecutablePath:argv[1] parentProcessId:atoi(argv[2])] autorelease];
[[NSApplication sharedApplication] run];

[pool release];

return EXIT_SUCCESS;
}

关于objective-c - 重新启动 cocoa 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3145701/

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