4 * Copyright (c) 2009 Nicholas Marriott <nicholas.marriott@gmail.com>
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>
22 #include <sys/sysctl.h>
32 #define is_runnable(p) \
33 ((p)->p_stat == LSRUN || (p)->p_stat == SIDL)
34 #define is_stopped(p) \
35 ((p)->p_stat == SSTOP || (p)->p_stat == SZOMB)
37 struct kinfo_proc2
*cmp_procs(struct kinfo_proc2
*, struct kinfo_proc2
*);
40 cmp_procs(struct kinfo_proc2
*p1
, struct kinfo_proc2
*p2
)
42 if (is_runnable(p1
) && !is_runnable(p2
))
44 if (!is_runnable(p1
) && is_runnable(p2
))
47 if (is_stopped(p1
) && !is_stopped(p2
))
49 if (!is_stopped(p1
) && is_stopped(p2
))
52 if (p1
->p_estcpu
> p2
->p_estcpu
)
54 if (p1
->p_estcpu
< p2
->p_estcpu
)
57 if (p1
->p_slptime
< p2
->p_slptime
)
59 if (p1
->p_slptime
> p2
->p_slptime
)
62 if (p1
->p_pid
> p2
->p_pid
)
68 osdep_get_name(int fd
, __unused
char *tty
)
73 struct kinfo_proc2
*buf
, *newbuf
, *bestp
;
76 if (stat(tty
, &sb
) == -1)
78 if ((mib
[3] = tcgetpgrp(fd
)) == -1)
86 mib
[2] = KERN_PROC_PGRP
;
92 if (sysctl(mib
, __arraycount(mib
), NULL
, &len
, NULL
, 0) == -1)
95 if ((newbuf
= realloc(buf
, len
)) == NULL
)
99 mib
[5] = len
/ (sizeof *buf
);
100 if (sysctl(mib
, __arraycount(mib
), buf
, &len
, NULL
, 0) == -1) {
107 for (i
= 0; i
< len
/ (sizeof *buf
); i
++) {
108 if (buf
[i
].p_tdev
!= sb
.st_rdev
)
113 bestp
= cmp_procs(&buf
[i
], bestp
);
118 name
= strdup(bestp
->p_comm
);
129 osdep_get_cwd(int fd
)
131 static char target
[PATH_MAX
+ 1];
141 if ((pgrp
= tcgetpgrp(fd
)) == -1)
146 mib
[1] = KERN_PROC_ARGS
;
148 mib
[3] = KERN_PROC_CWD
;
149 len
= sizeof(target
);
150 if (sysctl(mib
, __arraycount(mib
), target
, &len
, NULL
, 0) == 0)
153 xasprintf(&path
, "/proc/%lld/cwd", (long long) pgrp
);
154 n
= readlink(path
, target
, sizeof(target
) - 1);
166 osdep_event_init(void)
168 return (event_init());