4 * Copyright (c) 2009 Nicholas Marriott <nicm@users.sourceforge.net>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/param.h>
21 #include <sys/sysctl.h>
32 struct kinfo_proc
*cmp_procs(struct kinfo_proc
*, struct kinfo_proc
*);
33 char *osdep_get_name(int, char *);
34 char *osdep_get_cwd(int);
35 struct event_base
*osdep_event_init(void);
38 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
41 #define is_runnable(p) \
42 ((p)->kp_stat == SACTIVE || (p)->kp_stat == SIDL)
43 #define is_stopped(p) \
44 ((p)->kp_stat == SSTOP || (p)->kp_stat == SZOMB)
47 cmp_procs(struct kinfo_proc
*p1
, struct kinfo_proc
*p2
)
49 if (is_runnable(p1
) && !is_runnable(p2
))
51 if (!is_runnable(p1
) && is_runnable(p2
))
54 if (is_stopped(p1
) && !is_stopped(p2
))
56 if (!is_stopped(p1
) && is_stopped(p2
))
59 if (strcmp(p1
->kp_comm
, p2
->kp_comm
) < 0)
61 if (strcmp(p1
->kp_comm
, p2
->kp_comm
) > 0)
64 if (p1
->kp_pid
> p2
->kp_pid
)
70 osdep_get_name(int fd
, char *tty
)
72 int mib
[4] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PGRP
, 0 };
75 struct kinfo_proc
*buf
, *newbuf
, *bestp
;
81 if (stat(tty
, &sb
) == -1)
83 if ((mib
[3] = tcgetpgrp(fd
)) == -1)
87 if (sysctl(mib
, nitems(mib
), NULL
, &len
, NULL
, 0) == -1)
91 if ((newbuf
= realloc(buf
, len
)) == NULL
)
95 if (sysctl(mib
, nitems(mib
), buf
, &len
, NULL
, 0) == -1) {
102 for (i
= 0; i
< len
/ sizeof (struct kinfo_proc
); i
++) {
103 if (buf
[i
].kp_tdev
!= sb
.st_rdev
)
108 bestp
= cmp_procs(&buf
[i
], bestp
);
113 name
= strdup(bestp
->kp_comm
);
124 osdep_get_cwd(int fd
)
130 osdep_event_init(void)
132 return (event_init());