我如何通过编程的方式获取os x中的所有进程名?不仅仅是应用程序进程
问题描述:
我想获取os x系统中进程信息的快照。我如何通过编程的方式获取os x中的所有进程名?不仅仅是应用程序进程
'NSProcessInfo'只能获取调用进程的信息。
PS CMD可以是一个解决方案,但我想要一个C或Objective-C程序。
答
下面是一个使用libproc.h遍历系统上所有进程并确定它们有多少属于进程的有效用户的示例。您可以根据自己的需要轻松修改。
- (NSUInteger)maxSystemProcs
{
int32_t maxproc;
size_t len = sizeof(maxproc);
sysctlbyname("kern.maxproc", &maxproc, &len, NULL, 0);
return (NSUInteger)maxproc;
}
- (NSUInteger)runningUserProcs
{
NSUInteger maxSystemProcs = self.maxSystemProcs;
pid_t * const pids = calloc(maxSystemProcs, sizeof(pid_t));
NSAssert(pids, @"Memory allocation failure.");
const int pidcount = proc_listallpids(pids, (int)(maxSystemProcs * sizeof(pid_t)));
NSUInteger userPids = 0;
uid_t uid = geteuid();
for (int *pidp = pids; *pidp; pidp++) {
struct proc_bsdshortinfo bsdshortinfo;
int writtenSize;
writtenSize = proc_pidinfo(*pidp, PROC_PIDT_SHORTBSDINFO, 0, &bsdshortinfo, sizeof(bsdshortinfo));
if (writtenSize != (int)sizeof(bsdshortinfo)) {
continue;
}
if (bsdshortinfo.pbsi_uid == uid) {
userPids++;
}
}
free(pids);
return (NSUInteger)userPids;
}
我已经通过libc方法“proc_listallpids”&&“proc_pidpath”得到了解决方案。 – shaoheng
注意:'proc_name'只能获取应用程序的进程名称,其他进程名称(如daemon)将不会被获取。 – shaoheng