Dưới đây là một số hiện thực và chi tiết cụ thể, lưu ý rằng proc-> kp_proc.p_comm có một giới hạn độ dài nhân vật đó là lý do tại sao tôi đang thực hiện infoForPID: thay vì
Cocoa:
[NSWorkspace launchedApplications] (10.2+, không dùng nữa tại 10.7, niêm yết quá trình rất hạn chế) [NSWorkspace runningApplications] (10.6 +, quá trình ít hạn chế niêm yết nhưng vẫn không bao gồm các quy trình daemon)
Carbon:
- (NSArray*)getCarbonProcessList
{
NSMutableArray *ret = [NSMutableArray arrayWithCapacity:1];
ProcessSerialNumber psn = { kNoProcess, kNoProcess };
while (GetNextProcess(&psn) == noErr) {
CFDictionaryRef cfDict = ProcessInformationCopyDictionary(&psn, kProcessDictionaryIncludeAllInformationMask);
if (cfDict) {
NSDictionary *dict = (NSDictionary *)cfDict;
[ret addObject:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"%@",[dict objectForKey:(id)kCFBundleNameKey]],@"pname",
[NSString stringWithFormat:@"%@",[dict objectForKey:@"pid"]],@"pid",
[NSString stringWithFormat:@"%d",(uid_t)getuid()],@"uid",
nil]];
CFRelease(cfDict);
}
}
return ret;
}
C: (xem Technical Q&A QA1123 Getting List of All Processes on Mac OS X)
- (NSArray*)getBSDProcessList
{
NSMutableArray *ret = [NSMutableArray arrayWithCapacity:1];
kinfo_proc *mylist;
size_t mycount = 0;
mylist = (kinfo_proc *)malloc(sizeof(kinfo_proc));
GetBSDProcessList(&mylist, &mycount);
int k;
for(k = 0; k < mycount; k++) {
kinfo_proc *proc = NULL;
proc = &mylist[k];
NSString *fullName = [[self infoForPID:proc->kp_proc.p_pid] objectForKey:(id)kCFBundleNameKey];
if (fullName == nil) fullName = [NSString stringWithFormat:@"%s",proc->kp_proc.p_comm];
[ret addObject:[NSDictionary dictionaryWithObjectsAndKeys:
fullName,@"pname",
[NSString stringWithFormat:@"%d",proc->kp_proc.p_pid],@"pid",
[NSString stringWithFormat:@"%d",proc->kp_eproc.e_ucred.cr_uid],@"uid",
nil]];
}
free(mylist);
return ret;
}
- (NSDictionary *)infoForPID:(pid_t)pid
{
NSDictionary *ret = nil;
ProcessSerialNumber psn = { kNoProcess, kNoProcess };
if (GetProcessForPID(pid, &psn) == noErr) {
CFDictionaryRef cfDict = ProcessInformationCopyDictionary(&psn,kProcessDictionaryIncludeAllInformationMask);
ret = [NSDictionary dictionaryWithDictionary:(NSDictionary *)cfDict];
CFRelease(cfDict);
}
return ret;
}
Bạn có thể không muốn sử dụng các chức năng cũ hơn vì Apple có thể chọn không dùng nữa. Các lớp cacao nói chung là an toàn hơn về mặt này. – ericg
FYI, 'GetBSDProcessList' là * nhiều * nhanh hơn việc lặp lại thông qua Trình quản lý Quy trình. –
Trình quản lý quy trình hiện không được chấp nhận và có sẵn trong 64 bit. Tôi không nghĩ rằng nó có một cái rìu trên đầu nó theo cách mà một số API khác có. –