-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathpid.h
64 lines (47 loc) · 1.59 KB
/
pid.h
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
#include <unistd.h>
#include <sys/sysctl.h>
#include <pwd.h>
static inline int pidForProcess(NSString *name) {
// Thanks to http://stackoverflow.com/questions/6610705/how-to-get-process-id-in-iphone-or-ipad
// Faster than ps,grep,etc
int pid = 0;
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 0;
}
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)
{
for (int i = nprocess - 1; i >= 0; i--)
{
NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
if ([processName rangeOfString:name].location != NSNotFound)
{
pid = process[i].kp_proc.p_pid;
}
}
free(process);
}
}
}
return pid;
}