Relaunch an application


/ Published in: Objective C
Save to your folder(s)

The application that needs to be restarted must fork 'relaunch' with two arguments, then terminate. In Cocoa, the fork is easily achieved with a NSTask. The first argument must be the path to the application to relaunch. The second argument must be the process identifier of the terminating application. In Cocoa, you can get it with [[NSProcessInfo processInfo] processIdentifier], which is equivalent to getpid().


Copy this code and paste it in your HTML
  1. // gcc -Wall -arch i386 -arch ppc -mmacosx-version-min=10.4 -Os -framework AppKit -o relaunch relaunch.m
  2.  
  3. #import <AppKit/AppKit.h>
  4.  
  5. @interface TerminationListener : NSObject
  6. {
  7. const char *executablePath;
  8. pid_t parentProcessId;
  9. }
  10.  
  11. - (void) relaunch;
  12.  
  13. @end
  14.  
  15. @implementation TerminationListener
  16.  
  17. - (id) initWithExecutablePath:(const char *)execPath parentProcessId:(pid_t)ppid
  18. {
  19. self = [super init];
  20. if (self != nil) {
  21. executablePath = execPath;
  22. parentProcessId = ppid;
  23.  
  24. // This adds the input source required by the run loop
  25. [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationDidTerminate:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
  26. if (getppid() == 1) {
  27. // ppid is launchd (1) => parent terminated already
  28. [self relaunch];
  29. }
  30. }
  31. return self;
  32. }
  33.  
  34. - (void) applicationDidTerminate:(NSNotification *)notification
  35. {
  36. if (parentProcessId == [[[notification userInfo] valueForKey:@"NSApplicationProcessIdentifier"] intValue]) {
  37. // parent just terminated
  38. [self relaunch];
  39. }
  40. }
  41.  
  42. - (void) relaunch
  43. {
  44. [[NSWorkspace sharedWorkspace] launchApplication:[NSString stringWithUTF8String:executablePath]];
  45. exit(0);
  46. }
  47.  
  48. @end
  49.  
  50. int main (int argc, const char * argv[])
  51. {
  52. if (argc != 3) return EXIT_FAILURE;
  53.  
  54. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  55.  
  56. [[[TerminationListener alloc] initWithExecutablePath:argv[1] parentProcessId:atoi(argv[2])] autorelease];
  57. [[NSApplication sharedApplication] run];
  58.  
  59. [pool release];
  60.  
  61. return EXIT_SUCCESS;
  62. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.