我需要找出Mac OS上的SystemUIServer進程的pid,以便將其交給AXUIElementCreateApplication(pid);如何在Mac OS上找到C/C++/Objective-C中SystemUIServer進程的PID?
在shell上,這很容易通過ps,但我怎麼能在C/C++或Objective-C中做到這一點?
我需要找出Mac OS上的SystemUIServer進程的pid,以便將其交給AXUIElementCreateApplication(pid);如何在Mac OS上找到C/C++/Objective-C中SystemUIServer進程的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;
}
}
}
}
您還可以使用UIElementUtilities by Apple(它有助於管理AXUIElementRef情況下),以獲得進程的名稱。
嗨蘇多,非常感謝您的意見。我沒有爲我開箱工作,但給了我足夠的解決方案(見下面的答案)。 – Alex 2015-02-09 19:55:02
由於須藤,雅虎和谷歌,我發現了以下解決方案:
#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;
}
看一看'fork'和'execv'到你的應用程序中啓動'ps',[系統調用fork()和execv函數](http://stackoverflow.com/questions/19147386/system-call-fork-and-execv-function) – 2015-02-07 01:40:16
好吧,這將是一個解決方法......但它不可能通過系統調用? – Alex 2015-02-07 01:41:09
看起來你可以通過'KVM_ *'系列函數,這就是'ps'使用的。我會開始[這裏](http://stackoverflow.com/questions/2838190/mac-os-x-getting-detailed-process-information-specifically-its-launch-argument)。 – 2015-02-07 01:50:36