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>
30 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
33 #define is_runnable(p) \
34 ((p)->p_stat == SRUN || (p)->p_stat == SIDL || (p)->p_stat == SONPROC)
35 #define is_stopped(p) \
36 ((p)->p_stat == SSTOP || (p)->p_stat == SZOMB || (p)->p_stat == SDEAD)
38 struct kinfo_proc
*cmp_procs(struct kinfo_proc
*, struct kinfo_proc
*);
39 char *get_proc_name(int, char *);
40 char *get_proc_cwd(int);
43 cmp_procs(struct kinfo_proc
*p1
, struct kinfo_proc
*p2
)
45 if (is_runnable(p1
) && !is_runnable(p2
))
47 if (!is_runnable(p1
) && is_runnable(p2
))
50 if (is_stopped(p1
) && !is_stopped(p2
))
52 if (!is_stopped(p1
) && is_stopped(p2
))
55 if (p1
->p_estcpu
> p2
->p_estcpu
)
57 if (p1
->p_estcpu
< p2
->p_estcpu
)
60 if (p1
->p_slptime
< p2
->p_slptime
)
62 if (p1
->p_slptime
> p2
->p_slptime
)
65 if ((p1
->p_flag
& P_SINTR
) && !(p2
->p_flag
& P_SINTR
))
67 if (!(p1
->p_flag
& P_SINTR
) && (p2
->p_flag
& P_SINTR
))
70 if (strcmp(p1
->p_comm
, p2
->p_comm
) < 0)
72 if (strcmp(p1
->p_comm
, p2
->p_comm
) > 0)
75 if (p1
->p_pid
> p2
->p_pid
)
81 get_proc_name(int fd
, char *tty
)
83 int mib
[6] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PGRP
, 0,
84 sizeof(struct kinfo_proc
), 0 };
87 struct kinfo_proc
*buf
, *newbuf
, *bestp
;
93 if (stat(tty
, &sb
) == -1)
95 if ((mib
[3] = tcgetpgrp(fd
)) == -1)
99 if (sysctl(mib
, nitems(mib
), NULL
, &len
, NULL
, 0) == -1)
103 if ((newbuf
= realloc(buf
, len
)) == NULL
)
107 mib
[5] = (int)(len
/ sizeof(struct kinfo_proc
));
108 if (sysctl(mib
, nitems(mib
), buf
, &len
, NULL
, 0) == -1) {
115 for (i
= 0; i
< len
/ sizeof (struct kinfo_proc
); i
++) {
116 if ((dev_t
)buf
[i
].p_tdev
!= sb
.st_rdev
)
121 bestp
= cmp_procs(&buf
[i
], bestp
);
126 name
= strdup(bestp
->p_comm
);
139 int name
[] = { CTL_KERN
, KERN_PROC_CWD
, 0 };
140 static char path
[MAXPATHLEN
];
141 size_t pathlen
= sizeof path
;
143 if ((name
[2] = tcgetpgrp(fd
)) == -1)
145 if (sysctl(name
, 3, path
, &pathlen
, NULL
, 0) != 0)