How do I programmatically get the active processes running in the background, CPU and RAM usage for iOS?
Asked
Active
Viewed 2.0k times
4
-
2Use sysctl. See http://stackoverflow.com/questions/4312613/can-we-retrieve-the-applications-currently-running-in-iphone-and-ipad – EricS Feb 18 '12 at 21:49
2 Answers
5
The code self-explain :)
#import <mach/mach.h>
#import <mach/mach_host.h>
#import <sys/sysctl.h>
- (NSArray *)runningProcesses {
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
size_t miblen = 4;
size_t size;
int st = sysctl(mib, miblen, NULL, &size, NULL, 0);
struct kinfo_proc * process = NULL;
struct kinfo_proc * newprocess = NULL;
do {
size += size / 10;
newprocess = realloc(process, size);
if (!newprocess){
if (process){
free(process);
}
return nil;
}
process = newprocess;
st = sysctl(mib, miblen, process, &size, NULL, 0);
} while (st == -1 && errno == ENOMEM);
if (st == 0){
if (size % sizeof(struct kinfo_proc) == 0){
int nprocess = size / sizeof(struct kinfo_proc);
if (nprocess){
NSMutableArray * array = [[NSMutableArray alloc] init];
for (int i = nprocess - 1; i >= 0; i--){
NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessName", nil]];
[array addObject:dict];
}
free(process);
return array;
}
}
}
return nil;
}

Huynh Inc
- 2,010
- 1
- 25
- 42
3
CPU usage was retrieved here: iOS - Get CPU usage from application
RAM usage seems to be addressed here: Available memory for iPhone OS app
Edit:
Like EricS has pointed out in comments, there seems to be a way to get background tasks: Can we retrieve the applications currently running in iPhone and iPad and How to get information about free memory and running processes in an App Store approved app? (Yes, there is one!)