1

I need to find out the pid of the SystemUIServer process on Mac OS in order to hand it over to AXUIElementCreateApplication(pid);

On the shell this is easily possibly via ps but how can I do it in C/C++ or Objective-C?

Alex
  • 267
  • 1
  • 2
  • 7
  • Have a look at `fork` and `execv` to launch `ps` within your application, [System Call fork() and execv function](http://stackoverflow.com/questions/19147386/system-call-fork-and-execv-function) – James Moore Feb 07 '15 at 01:40
  • OK that would be a work around... but is it not possible via a system call? – Alex Feb 07 '15 at 01:41
  • It looks like you can through the `KVM_*` family of functions, this is what `ps` uses. I would start [here](http://stackoverflow.com/questions/2838190/mac-os-x-getting-detailed-process-information-specifically-its-launch-argument). – James Moore Feb 07 '15 at 01:50

2 Answers2

2

I would check through all running processes.

pid_t resultPid = -1;
NSArray *runningApplications = [[NSWorkspace sharedWorkspace] runningApplications];
for (NSRunningApplication *app in runningApplications) {
    pid_t pid = [app processIdentifier];
    if (pid != ((pid_t)-1)) {
        AXUIElementRef appl = AXUIElementCreateApplication(pid);
        id result = nil;
        if(AXUIElementCopyAttributeValue(appl, (CFStringRef)NSAccessibilityTitleAttribute, (void *)&result) == kAXErrorSuccess) {
            if([((NSString*)result) isEqualToString:@"SystemUIServer"]){
                resultPid = pid;
                break;
            }      
        }
    }
}

You can also use UIElementUtilities by Apple (it helps manage AXUIElementRef instances) to get the name of the process.

Sudo
  • 991
  • 9
  • 24
  • Hi Sudo, thank you very much for you input. I didn't work for me out of the box but gave me enough to find a solution (see answer below). – Alex Feb 09 '15 at 19:55
0

Thanks to Sudo, Yahoo and Google I found the following solution:

#include <libproc.h>

int getPid(const char* processname)
{
  pid_t resultPid = -1;
  NSArray *runningApplications = [[NSWorkspace sharedWorkspace] runningApplications];

  for (NSRunningApplication *app in runningApplications) {
    pid_t pid = [app processIdentifier];
    if (pid != ((pid_t)-1)) {

      char nameBuffer[512];
      proc_name(pid, nameBuffer, sizeof(nameBuffer));

      if(!strcmp(processname,nameBuffer)) {
         resultPid=pid;
         break;
      }
    }
  }

  return resultPid;
}
Alex
  • 267
  • 1
  • 2
  • 7