简体   繁体   中英

How can I find out the PID of the SystemUIServer process in C/C++/Objective-C on Mac OS?

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?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM