[英]How can I find out the PID of the SystemUIServer process in C/C++/Objective-C on Mac OS?
我需要找出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,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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.