以下是一些具体的实现和细节,请注意 proc->kp_proc.p_comm 有字符长度限制,这就是我实现 infoForPID: 的原因
Cocoa :
[NSWorkspace LaunchedApplications](10.2+,在 10.7 中已弃用,进程列表非常有限)
[NSWorkspace runningApplications](10.6+,进程列表限制较少,但仍然不包括守护进程)
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: (see 技术问答 QA1123 获取 Mac OS X 上所有进程的列表 http://developer.apple.com/legacy/mac/library/#qa/qa2001/qa1123.html )
- (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;
}