1 /* $NetBSD: ps.c,v 1.73 2009/02/14 08:04:10 lukem Exp $ */
4 * Copyright (c) 2000-2008 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
33 * Copyright (c) 1990, 1993, 1994
34 * The Regents of the University of California. All rights reserved.
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61 #include <sys/cdefs.h>
63 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\
64 The Regents of the University of California. All rights reserved.");
69 static char sccsid
[] = "@(#)ps.c 8.4 (Berkeley) 4/2/94";
71 __RCSID("$NetBSD: ps.c,v 1.73 2009/02/14 08:04:10 lukem Exp $");
75 #include <sys/param.h>
78 #include <sys/resource.h>
82 #include <sys/ioctl.h>
83 #include <sys/sysctl.h>
104 * ARGOPTS must contain all option characters that take arguments
105 * (except for 't'!) - it is used in kludge_oldps_options()
107 #define GETOPTSTR "aAcCeghjk:LlM:mN:O:o:p:rSsTt:U:uvW:wx"
108 #define ARGOPTS "kMNOopUW"
110 struct kinfo_proc2
*kinfo
;
111 struct varlist displaylist
= SIMPLEQ_HEAD_INITIALIZER(displaylist
);
112 struct varlist sortlist
= SIMPLEQ_HEAD_INITIALIZER(sortlist
);
114 int eval
; /* exit value */
116 int sumrusage
; /* -S */
117 int termwidth
; /* width of screen (0 == infinity) */
118 int totwidth
; /* calculated width of requested variables */
120 int needcomm
, needenv
, commandonly
;
123 static struct kinfo_lwp
124 *pick_representative_lwp(struct kinfo_proc2
*,
125 struct kinfo_lwp
*, int);
126 static struct kinfo_proc2
127 *getkinfo_kvm(kvm_t
*, int, int, int *);
128 static char *kludge_oldps_options(char *);
129 static int pscomp(const void *, const void *);
130 static void scanvars(void);
131 static void usage(void);
132 static int parsenum(const char *, const char *);
133 int main(int, char *[]);
135 char dfmt
[] = "pid tt state time command";
136 char jfmt
[] = "user pid ppid pgid sess jobc state tt time command";
137 char lfmt
[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
138 char sfmt
[] = "uid pid ppid cpu lid nlwp pri nice vsz rss wchan lstate tt "
140 char ufmt
[] = "user pid %cpu %mem vsz rss tt state start time command";
141 char vfmt
[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
143 const char *default_fmt
= dfmt
;
145 struct varent
*Opos
= NULL
; /* -O flag inserts after this point */
150 main(int argc
, char *argv
[])
154 struct kinfo_lwp
*kl
, *l
;
155 int ch
, i
, j
, fmt
, lineno
, nentries
, nlwps
;
157 int prtheader
, wflag
, what
, xflg
, mode
, showlwps
;
158 char *nlistf
, *memf
, *swapf
, errbuf
[_POSIX2_LINE_MAX
];
161 setprogname(argv
[0]);
162 (void)setlocale(LC_ALL
, "");
164 if ((ioctl(STDOUT_FILENO
, TIOCGWINSZ
, (char *)&ws
) == -1 &&
165 ioctl(STDERR_FILENO
, TIOCGWINSZ
, (char *)&ws
) == -1 &&
166 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ws
) == -1) ||
170 termwidth
= ws
.ws_col
- 1;
175 argv
[1] = kludge_oldps_options(argv
[1]);
177 fmt
= prtheader
= wflag
= xflg
= showlwps
= 0;
178 what
= KERN_PROC_UID
;
179 flag
= myuid
= getuid();
180 memf
= nlistf
= swapf
= NULL
;
182 while ((ch
= getopt(argc
, argv
, GETOPTSTR
)) != -1)
185 /* "-A" shows all processes, like "-ax" */
189 what
= KERN_PROC_ALL
;
195 case 'e': /* XXX set ufmt */
204 prtheader
= ws
.ws_row
> 5 ? ws
.ws_row
: 22;
215 break; /* no-op - was dontuseprocfs */
236 * If this is not the first -O option, insert
237 * just after the previous one.
239 * If there is no format yet, start with the default
240 * format, and insert after the pid column.
242 * If there is already a format, insert after
243 * the pid column, or at the end if there's no
248 parsefmt(default_fmt
);
249 Opos
= varlist_find(&displaylist
, "pid");
251 parsefmt_insert(optarg
, &Opos
);
259 what
= KERN_PROC_PID
;
260 flag
= parsenum(optarg
, "process id");
270 /* -L was already taken... */
275 if ((ttname
= ttyname(STDIN_FILENO
)) == NULL
)
276 errx(1, "stdin: not a terminal");
283 char pathbuf
[MAXPATHLEN
];
287 if (strcmp(ttname
, "?") == 0) {
288 flag
= KERN_PROC_TTY_NODEV
;
290 } else if (strcmp(ttname
, "-") == 0)
291 flag
= KERN_PROC_TTY_REVOKE
;
292 else if (strcmp(ttname
, "co") == 0)
293 ttypath
= _PATH_CONSOLE
;
294 else if (strncmp(ttname
, "pts/", 4) == 0 ||
295 strncmp(ttname
, "tty", 3) == 0) {
296 (void)snprintf(pathbuf
,
297 sizeof(pathbuf
), "%s%s", _PATH_DEV
, ttname
);
299 } else if (*ttname
!= '/') {
300 (void)snprintf(pathbuf
,
301 sizeof(pathbuf
), "%s%s", _PATH_TTY
, ttname
);
305 what
= KERN_PROC_TTY
;
307 if (stat(ttypath
, &sb
) == -1)
308 err(1, "%s", ttypath
);
309 if (!S_ISCHR(sb
.st_mode
))
310 errx(1, "%s: not a terminal", ttypath
);
316 if (*optarg
!= '\0') {
319 what
= KERN_PROC_UID
;
320 pw
= getpwnam(optarg
);
322 flag
= parsenum(optarg
, "user name");
344 termwidth
= UNLIMITED
;
345 else if (termwidth
< 131)
359 #define BACKWARD_COMPATIBILITY
360 #ifdef BACKWARD_COMPATIBILITY
372 kd
= kvm_openfiles(NULL
, NULL
, NULL
, KVM_NO_FILES
, errbuf
);
375 kd
= kvm_openfiles(nlistf
, memf
, swapf
, O_RDONLY
, errbuf
);
378 errx(1, "%s", errbuf
);
381 parsefmt(default_fmt
);
383 /* Add default sort criteria */
384 parsesort("tdev,pid");
385 SIMPLEQ_FOREACH(vent
, &sortlist
, next
) {
386 if (vent
->var
->flag
& LWP
|| vent
->var
->type
== UNSPECIFIED
)
387 warnx("Cannot sort on %s, sort key ignored\n",
392 * scan requested variables, noting what structures are needed.
399 if (!(kinfo
= getkinfo_kvm(kd
, what
, flag
, &nentries
)))
400 err(1, "%s", kvm_geterr(kd
));
408 qsort(kinfo
, nentries
, sizeof(struct kinfo_proc2
), pscomp
);
410 * For each proc, call each variable output function in
411 * "setwidth" mode to determine the widest element of
414 if (mode
== PRINTMODE
)
415 for (i
= 0; i
< nentries
; i
++) {
416 struct kinfo_proc2
*ki
= &kinfo
[i
];
418 if (xflg
== 0 && (ki
->p_tdev
== (uint32_t)NODEV
||
419 (ki
->p_flag
& P_CONTROLT
) == 0))
422 kl
= kvm_getlwps(kd
, ki
->p_pid
, ki
->p_paddr
,
423 sizeof(struct kinfo_lwp
), &nlwps
);
427 l
= pick_representative_lwp(ki
, kl
, nlwps
);
428 SIMPLEQ_FOREACH(vent
, &displaylist
, next
)
429 OUTPUT(vent
, ki
, l
, WIDTHMODE
);
431 /* The printing is done with the loops
432 * reversed, but here we don't need that,
433 * and this improves the code locality a bit.
435 SIMPLEQ_FOREACH(vent
, &displaylist
, next
)
436 for (j
= 0; j
< nlwps
; j
++)
437 OUTPUT(vent
, ki
, &kl
[j
],
442 * Print header - AFTER determining process field widths.
443 * printheader() also adds up the total width of all
444 * fields the first time it's called.
448 * For each proc, call each variable output function in
451 for (i
= lineno
= 0; i
< nentries
; i
++) {
452 struct kinfo_proc2
*ki
= &kinfo
[i
];
454 if (xflg
== 0 && (ki
->p_tdev
== (uint32_t)NODEV
||
455 (ki
->p_flag
& P_CONTROLT
) == 0))
457 kl
= kvm_getlwps(kd
, ki
->p_pid
, (u_long
)ki
->p_paddr
,
458 sizeof(struct kinfo_lwp
), &nlwps
);
462 l
= pick_representative_lwp(ki
, kl
, nlwps
);
463 SIMPLEQ_FOREACH(vent
, &displaylist
, next
) {
464 OUTPUT(vent
, ki
, l
, mode
);
465 if (SIMPLEQ_NEXT(vent
, next
) != NULL
)
469 if (prtheader
&& lineno
++ == prtheader
- 4) {
475 for (j
= 0; j
< nlwps
; j
++) {
476 SIMPLEQ_FOREACH(vent
, &displaylist
, next
) {
477 OUTPUT(vent
, ki
, &kl
[j
], mode
);
478 if (SIMPLEQ_NEXT(vent
, next
) != NULL
)
482 if (prtheader
&& lineno
++ == prtheader
- 4) {
494 static struct kinfo_lwp
*
495 pick_representative_lwp(struct kinfo_proc2
*ki
, struct kinfo_lwp
*kl
, int nlwps
)
497 int i
, onproc
, running
, sleeping
, stopped
, suspended
;
498 static struct kinfo_lwp zero_lwp
;
503 /* Trivial case: only one LWP */
507 switch (ki
->p_realstat
) {
510 /* Pick the most live LWP */
511 onproc
= running
= sleeping
= stopped
= suspended
= -1;
512 for (i
= 0; i
< nlwps
; i
++) {
513 switch (kl
[i
].l_stat
) {
536 return &kl
[sleeping
];
540 return &kl
[suspended
];
547 /* Error condition! */
548 warnx("Inconsistent LWP state for process %d\n", ki
->p_pid
);
553 static struct kinfo_proc2
*
554 getkinfo_kvm(kvm_t
*kdp
, int what
, int flag
, int *nentriesp
)
557 return (kvm_getproc2(kdp
, what
, flag
, sizeof(struct kinfo_proc2
),
567 SIMPLEQ_FOREACH(vent
, &displaylist
, next
) {
569 if (v
->flag
& COMM
) {
577 pscomp(const void *a
, const void *b
)
579 const struct kinfo_proc2
*ka
= (const struct kinfo_proc2
*)a
;
580 const struct kinfo_proc2
*kb
= (const struct kinfo_proc2
*)b
;
586 const sigset_t
*sa
, *sb
;
588 #define V_SIZE(k) ((k)->p_vm_msize)
589 #define RDIFF_N(t, n) \
590 if (((const t *)((const char *)ka + v->off))[n] > ((const t *)((const char *)kb + v->off))[n]) \
592 if (((const t *)((const char *)ka + v->off))[n] < ((const t *)((const char *)kb + v->off))[n]) \
595 #define RDIFF(type) RDIFF_N(type, 0); continue
597 SIMPLEQ_FOREACH(ve
, &sortlist
, next
) {
600 /* LWP structure not available (yet) */
602 /* Sort on pvar() fields, + a few others */
625 sa
= (const void *)((const char *)a
+ v
->off
);
626 sb
= (const void *)((const char *)b
+ v
->off
);
629 if (sa
->__bits
[i
] > sb
->__bits
[i
])
631 if (sa
->__bits
[i
] < sb
->__bits
[i
])
634 } while (i
< (int)__arraycount(sa
->__bits
));
643 /* compare xxx_sec then xxx_usec */
644 RDIFF_N(uint32_t, 0);
645 RDIFF_N(uint32_t, 1);
648 i64
= ka
->p_rtime_sec
* 1000000 + ka
->p_rtime_usec
;
649 i64
-= kb
->p_rtime_sec
* 1000000 + kb
->p_rtime_usec
;
651 i64
+= ka
->p_uctime_sec
* 1000000
653 i64
-= kb
->p_uctime_sec
* 1000000
657 return i64
> 0 ? 1 : -1;
660 i
= getpcpu(kb
) - getpcpu(ka
);
665 i
= V_SIZE(kb
) - V_SIZE(ka
);
671 /* Ignore everything else */
681 * ICK (all for getopt), would rather hide the ugliness
682 * here than taint the main code.
687 * The old convention that 't' with no trailing tty arg means the user's
688 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
689 * feature is available with the option 'T', which takes no argument.
692 kludge_oldps_options(char *s
)
695 char *newopts
, *ns
, *cp
;
698 if ((newopts
= ns
= malloc(len
+ 3)) == NULL
)
701 * options begin with '-'
704 *ns
++ = '-'; /* add option flag */
706 * gaze to end of argv[1]
710 * if the last letter is a 't' flag and there are no other option
711 * characters that take arguments (eg U, p, o) in the option
712 * string and the option string doesn't start with a '-' then
713 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
715 if (*cp
== 't' && *s
!= '-' && strpbrk(s
, ARGOPTS
) == NULL
)
719 * otherwise check for trailing number, which *may* be a
722 while (cp
>= s
&& isdigit((unsigned char)*cp
))
726 memmove(ns
, s
, (size_t)(cp
- s
)); /* copy up to trailing number */
729 * if there's a trailing number, and not a preceding 'p' (pid) or
730 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
732 if (isdigit((unsigned char)*cp
) &&
733 (cp
== s
|| (cp
[-1] != 'U' && cp
[-1] != 't' && cp
[-1] != 'p' &&
734 cp
[-1] != '/' && (cp
- 1 == s
|| cp
[-2] != 't'))))
736 /* and append the number */
737 (void)strcpy(ns
, cp
); /* XXX strcpy is safe here */
743 parsenum(const char *str
, const char *msg
)
748 ul
= strtoul(str
, &ep
, 0);
750 if (*str
== '\0' || *ep
!= '\0')
751 errx(1, "Invalid %s: `%s'", msg
, str
);
754 errx(1, "Out of range %s: `%s'", msg
, str
);
763 (void)fprintf(stderr
,
764 "usage:\t%s\n\t %s\n\t%s\n",
765 "ps [-AaCcehjlmrSsTuvwx] [-k key] [-M core] [-N system] [-O fmt]",
766 "[-o fmt] [-p pid] [-t tty] [-U username] [-W swap]",