如何在Mac OS上的C / C ++ / Objective-C中找到SystemUIServer进程的PID?

时间:2015-02-07 01:31:30

标签: c++ objective-c macos pid

我需要在Mac OS上找出SystemUIServer进程的pid,以便将其交给AXUIElementCreateApplication(pid);

在shell上很容易通过ps,但我怎么能用C / C ++或Objective-C做呢?

2 个答案:

答案 0 :(得分:2)

我会检查所有正在运行的进程。

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

您还可以使用UIElementUtilities by Apple(它有助于管理AXUIElementRef实例)来获取进程的名称。

答案 1 :(得分:0)

感谢Sudo,Yahoo和Google,我找到了以下解决方案:

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