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

标签 objective-c cocoa process

我有一个应用程序检查其命令行参数并将值存储在持久存储中。其中之一是我不想让人们通过“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/

相关文章:

ios - TableView 中的自定义单元格 : Failed to obtain a cell from its Data Source

ios - Xcode 6 iOS 7 View 大小

json - NSTextview如何显示json格式的字符串

java - 运行不存在的 jar 不会导致任何异常/错误

C++ 使用参数启动进程

ios - 如何使用AVPlayer中的缓存播放ts文件?

cocoa - NSOpenPanel/NSSavePanel : How can I preselect a file before the dialog opens?

objective-c - 返回指向函数内分配的内存的指针

python - 在python中为迭代任务创建n个进程

objective-c - "double"在 ceil(double) 中做什么?