【问题标题】:How can I find out the PID of the SystemUIServer process in C/C++/Objective-C on Mac OS?如何在 Mac OS 上的 C/C++/Objective-C 中找出 SystemUIServer 进程的 PID?
【发布时间】:2015-02-07 01:31:30
【问题描述】:

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

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

【问题讨论】:

  • 查看forkexecv 以在您的应用程序中启动psSystem Call fork() and execv function
  • 好的,这将是一个解决方法......但是通过系统调用不可能吗?
  • 看起来您可以通过KVM_* 系列函数,这就是ps 使用的。我会开始here

标签: c++ objective-c macos pid


【解决方案1】:

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

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 实例)来获取进程的名称。

【讨论】:

  • 您好 Sudo,非常感谢您的输入。我没有开箱即用地为我工作,但给了我足够的帮助以找到解决方案(请参阅下面的答案)。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2018-06-18
    • 2010-12-31
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多