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

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

本文关键字:SystemUIServer PID 进程 Objective-C C++ Mac OS 上的      更新时间:2023-10-16

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

在shell上,这很容易通过ps实现,但我如何在C/C++或Objective-C中实现呢?

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

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

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

感谢Sudo、雅虎和谷歌,我找到了以下解决方案:

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