Hier ein Beispiel, in dem libproc.h verwendet wird, um alle Prozesse auf dem System zu durchlaufen und festzustellen, wie viele von ihnen zum effektiven Benutzer des Prozesses gehören. Sie können dies leicht für Ihre Bedürfnisse ändern.
- (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;
}
Ich habe die Lösung von libc-Methode "proc_listallpids" && "proc_pidpath". – shaoheng
Hinweis: 'proc_name' kann nur Prozessnamen des App-Programms erhalten, andere Prozessnamen (z. B. Daemon) werden nicht erhalten. – shaoheng