-
Notifications
You must be signed in to change notification settings - Fork 3
/
list-processes_bsd.c
51 lines (43 loc) · 962 Bytes
/
list-processes_bsd.c
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
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <fcntl.h>
#include <kvm.h>
#include <paths.h>
#include <sys/sysctl.h>
#include <sys/user.h>
bool kvm_cleanup(kvm_t *kd)
{
if (kvm_close(kd) == -1) {
printf("kvm_close() failed with error %d\n", errno);
return false;
}
return true;
}
int main()
{
char error[_POSIX2_LINE_MAX];
#ifdef KVM_NO_FILES
kvm_t *kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, error);
#else
kvm_t *kd = kvm_openfiles(NULL, _PATH_DEVNULL, NULL, O_RDONLY, error);
#endif
if (!kd) {
printf("kvm_open2() failed with error: %s\n", error);
return 1;
}
int n_procs;
struct kinfo_proc *procs_info = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_procs);
if (!procs_info) {
printf("kvm_getprocs() failed\n");
kvm_cleanup(kd);
return 2;
}
for (int i = 0; i < n_procs; ++i) {
printf("[%u] %s\n", procs_info[i].ki_pid, procs_info[i].ki_comm);
}
if (!kvm_cleanup(kd)) {
return 3;
}
return 0;
}