Last active
August 29, 2015 14:06
-
-
Save sasikiran/666099a5e116bee99800 to your computer and use it in GitHub Desktop.
UIDevice + Processes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import UIKit; | |
@interface UIDevice (Processes) | |
- (NSArray *)runningProcesses; | |
@end | |
#import "UIDevice+Processes.h" | |
#import <sys/sysctl.h> | |
@implementation UIDevice (Processes) | |
- (NSArray *)runningProcesses { | |
int mib[4] = { | |
CTL_KERN, | |
KERN_PROC, | |
KERN_PROC_ALL, | |
0 | |
}; | |
size_t miblength = 4; | |
size_t size; | |
int st = sysctl(mib, miblength, 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, miblength, process, &size, NULL, 0); | |
} while (st == -1 && errno == ENOMEM); | |
if (st == 0) { | |
if (size % sizeof(struct kinfo_proc) == 0) { | |
int numberOfRunningProcesses = size / sizeof(struct kinfo_proc); | |
if (numberOfRunningProcesses) { | |
NSMutableArray *mutableArray = [[NSMutableArray alloc] init]; | |
for (NSInteger i = numberOfRunningProcesses - 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:@[processID, processName] | |
forKeys:@[@"ProcessID", @"ProcessName"]]; | |
[mutableArray addObject:dict]; | |
} | |
free(process); | |
return mutableArray; | |
} | |
} | |
} | |
return nil; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment