Question

Before macosx 10.9 it was possible to detect if an executable was launched using launch services (finder, open, etc.) or directly invoked on the terminal by looking for the presence of a -psn_* argument in the program arguments.

This is no longer the case in 10.9. Is there a way of detecting that in 10.9 ? It seems I can look if cwd is / but that's not really foolproof.

Was it helpful?

Solution

Trying to see of you are a child of launchd may actually be the sane way of doing but the solution I want needs to be conservative about the system calls you use.

Here are two different approaches. One is to to check whether one of the standard file descriptors is a tty (that won't work if they all redirected though). Sample code:

#include <unistd.h>

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
  if (isatty (STDIN_FILENO) || isatty (STDOUT_FILENO) || isatty(STDERR_FILENO))
  { printf ("tty launch\n"); fflush (stdout); }
  else
  { NSLog (@"Launch service"); }
}

the other one is too look if the environment variable TERM is unset or, for open launches, if the environment variable _ is /usr/bin/open):

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
  NSDictionary *env = [[NSProcessInfo processInfo] environment];
  NSLog(@"%@",env);
  NSString* term = [env objectForKey:@"TERM"];
  NSString* underscore = [env objectForKey:@"_"];

  if (!term || [underscore isEqualTo:@"/usr/bin/open"])
  { NSLog (@"Launch service"); }
  else
  { printf ("tty launch\n"); fflush (stdout); }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top