您的位置:首页 > 移动开发

iOS 9已下的获取APP进程信息

2016-04-01 17:31 459 查看
- (NSDictionary *)getAppInfo:(NSString *)exec withBundleID:(NSString *)bundle
{
if ([exec isKindOfClass:[NSTimer class]])
{
exec = [(NSTimer *)exec userInfo];
}
NSDictionary * ret = nil;

int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
u_int miblen = 4;
size_t size = 0;
int st = 0;
struct kinfo_proc * process = NULL;
struct kinfo_proc * newprocess = NULL;

sysctl(mib, miblen, NULL, &size, NULL, 0);

do
{
size += size / 10;
newprocess = realloc(process, size);
if (!newprocess)
{
if (process)
{
free(process);
}
return ret;
}
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)
{
unsigned long nprocess = size / sizeof(struct kinfo_proc);
if (nprocess)
{
for (long i = nprocess - 1; i >= 0;  i --)
{
NSString * procExecName = [NSString stringWithCString:process[i].kp_proc.p_comm encoding:NSUTF8StringEncoding];
NSString * procBundleId = bundle;
long timeInterval = process[i].kp_proc.p_un.__p_starttime.tv_sec;

// !!!:时间转化
NSDateFormatter * format = [[NSDateFormatter alloc] init];
[format setDateStyle:NSDateFormatterMediumStyle];
[format setTimeStyle:NSDateFormatterShortStyle];
[format setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS'Z'"];
NSTimeZone * timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
[format setTimeZone:timeZone];

NSDate * oldTime = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDate * nowTime = [NSDate date];
NSString * procSTime    = [format stringFromDate:oldTime];
NSString * procETime    = [format stringFromDate:nowTime];

int t = [nowTime timeIntervalSince1970] - timeInterval;
NSString * procUTime    = [[NSNumber numberWithInt:t] stringValue];
// bundleid, execName, stime, etime,utime
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:procExecName forKey:@"KPROCEXECNAME"];
[dic setValue:procBundleId forKey:@"KPROBUNDLEID"];
[dic setValue:procSTime forKey:@"KPROCSTIME"];
[dic setValue:procETime forKey:@"kPROCETIME"];
[dic setValue:procUTime forKey:@"KPROCUTIME"];

ret = [NSDictionary dictionaryWithDictionary:dic];
}

free(process);

return ret;
}
}
}

free(process);
return ret;
}


需要的头文件为:

#import <sys/sysctl.h>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: