通过调用 sys/sysctl.h 读取系统内核获取进程列表 。
代码悦德财富:https://yuedecaifu.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
+(NSMutableArray *)runningProcesses { //指定名字参数,按照顺序第一个元素指定本请求定向到内核的哪个子系统,第二个及其后元素依次细化指定该系统的某个部分。 //CTL_KERN,KERN_PROC,KERN_PROC_ALL 正在运行的所有进程 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL ,0}; size_t miblen = 4; //值-结果参数:函数被调用时,size指向的值指定该缓冲区的大小;函数返回时,该值给出内核存放在该缓冲区中的数据量 //如果这个缓冲不够大,函数就返回ENOMEM错误 size_t size; //返回0,成功;返回-1,失败 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); process = NULL; } 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--) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString * processID = [[NSString alloc] initWithFormat:@ "%d" , process[i].kp_proc.p_pid]; NSString * processName = [[NSString alloc] initWithFormat:@ "%s" , process[i].kp_proc.p_comm]; NSString * proc_CPU = [[NSString alloc] initWithFormat:@ "%d" , process[i].kp_proc.p_pctcpu]; //the process duration //double t = [[NSDate date] timeIntervalSince1970] - process[i].kp_proc.p_un.__p_starttime.tv_sec; NSString * proc_useTiem = [[NSString alloc] initWithFormat:@ "%s" , asctime ( localtime (&(process[i].kp_proc.p_un.__p_starttime.tv_sec)))]; NSMutableDictionary *dic = [[NSMutableDictionary alloc] init]; [dic setValue:processID forKey:@ "ProcessID" ]; [dic setValue:processName forKey:@ "ProcessName" ]; [dic setValue:proc_CPU forKey:@ "ProcessCPU" ]; [dic setValue:proc_useTiem forKey:@ "ProcessUseTime" ]; [processID release]; [processName release]; [proc_CPU release]; [proc_useTiem release]; [array addObject:dic]; [dic release]; [pool release]; } free (process); process = NULL; return array; } } } return nil; } |