1 /* $NetBSD: ps.c,v 1.83 2015/06/16 22:31:08 christos 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.83 2015/06/16 22:31:08 christos Exp $");
75 #include <sys/param.h>
77 #include <sys/resource.h>
81 #include <sys/ioctl.h>
82 #include <sys/sysctl.h>
103 * ARGOPTS must contain all option characters that take arguments
104 * (except for 't'!) - it is used in kludge_oldps_options()
106 #define GETOPTSTR "aAcCeghjk:LlM:mN:O:o:p:rSsTt:U:uvW:wx"
107 #define ARGOPTS "kMNOopUW"
109 struct kinfo_proc2
*kinfo
;
110 struct varlist displaylist
= SIMPLEQ_HEAD_INITIALIZER(displaylist
);
111 struct varlist sortlist
= SIMPLEQ_HEAD_INITIALIZER(sortlist
);
113 int eval
; /* exit value */
115 int sumrusage
; /* -S */
116 int termwidth
; /* width of screen (0 == infinity) */
117 int totwidth
; /* calculated width of requested variables */
119 int needcomm
, needenv
, commandonly
;
122 static struct kinfo_lwp
123 *pick_representative_lwp(struct kinfo_proc2
*,
124 struct kinfo_lwp
*, int);
125 static struct kinfo_proc2
126 *getkinfo_kvm(kvm_t
*, int, int, int *);
127 static char *kludge_oldps_options(char *);
128 static int pscomp(const void *, const void *);
129 static void scanvars(void);
130 __dead
static void usage(void);
131 static int parsenum(const char *, const char *);
132 int main(int, char *[]);
134 char dfmt
[] = "pid tt state time command";
135 char jfmt
[] = "user pid ppid pgid sess jobc state tt time command";
136 char lfmt
[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
137 char sfmt
[] = "uid pid ppid cpu lid nlwp pri nice vsz rss wchan lstate tt "
139 char ufmt
[] = "user pid %cpu %mem vsz rss tt state start time command";
140 char vfmt
[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
142 const char *default_fmt
= dfmt
;
144 struct varent
*Opos
= NULL
; /* -O flag inserts after this point */
149 ttyname2dev(const char *ttname
, int *xflg
, int *what
)
153 char pathbuf
[MAXPATHLEN
];
156 if (strcmp(ttname
, "?") == 0) {
158 return KERN_PROC_TTY_NODEV
;
160 if (strcmp(ttname
, "-") == 0)
161 return KERN_PROC_TTY_REVOKE
;
163 if (strcmp(ttname
, "co") == 0)
164 ttypath
= _PATH_CONSOLE
;
165 else if (strncmp(ttname
, "pts/", 4) == 0 ||
166 strncmp(ttname
, "tty", 3) == 0) {
167 (void)snprintf(pathbuf
,
168 sizeof(pathbuf
), "%s%s", _PATH_DEV
, ttname
);
170 } else if (*ttname
!= '/') {
171 (void)snprintf(pathbuf
,
172 sizeof(pathbuf
), "%s%s", _PATH_TTY
, ttname
);
176 *what
= KERN_PROC_TTY
;
177 if (stat(ttypath
, &sb
) == -1) {
182 pts
= getdevmajor("pts", S_IFCHR
);
183 if (pts
!= NODEVMAJOR
&& strncmp(ttname
, "pts/", 4) == 0) {
184 int ptsminor
= atoi(ttname
+ 4);
186 snprintf(pathbuf
, sizeof(pathbuf
), "pts/%d", ptsminor
);
187 if (strcmp(pathbuf
, ttname
) == 0 && ptsminor
>= 0)
188 return makedev(pts
, ptsminor
);
191 err(1, "%s", ttypath
);
193 if (!S_ISCHR(sb
.st_mode
))
194 errx(1, "%s: not a terminal", ttypath
);
199 main(int argc
, char *argv
[])
203 struct kinfo_lwp
*kl
, *l
;
204 int ch
, i
, j
, fmt
, lineno
, nentries
, nlwps
;
206 int prtheader
, wflag
, what
, xflg
, showlwps
;
207 char *nlistf
, *memf
, *swapf
, errbuf
[_POSIX2_LINE_MAX
];
210 setprogname(argv
[0]);
211 (void)setlocale(LC_ALL
, "");
213 if ((ioctl(STDOUT_FILENO
, TIOCGWINSZ
, (char *)&ws
) == -1 &&
214 ioctl(STDERR_FILENO
, TIOCGWINSZ
, (char *)&ws
) == -1 &&
215 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ws
) == -1) ||
219 termwidth
= ws
.ws_col
- 1;
222 argv
[1] = kludge_oldps_options(argv
[1]);
224 fmt
= prtheader
= wflag
= xflg
= showlwps
= 0;
225 what
= KERN_PROC_UID
;
226 flag
= myuid
= getuid();
227 memf
= nlistf
= swapf
= NULL
;
229 while ((ch
= getopt(argc
, argv
, GETOPTSTR
)) != -1)
232 /* "-A" shows all processes, like "-ax" */
236 what
= KERN_PROC_ALL
;
242 case 'e': /* XXX set ufmt */
251 prtheader
= ws
.ws_row
> 5 ? ws
.ws_row
: 22;
262 break; /* no-op - was dontuseprocfs */
283 * If this is not the first -O option, insert
284 * just after the previous one.
286 * If there is no format yet, start with the default
287 * format, and insert after the pid column.
289 * If there is already a format, insert after
290 * the pid column, or at the end if there's no
295 parsefmt(default_fmt
);
296 Opos
= varlist_find(&displaylist
, "pid");
298 parsefmt_insert(optarg
, &Opos
);
306 what
= KERN_PROC_PID
;
307 flag
= parsenum(optarg
, "process id");
317 /* -L was already taken... */
322 if ((ttname
= ttyname(STDIN_FILENO
)) == NULL
)
323 errx(1, "stdin: not a terminal");
324 flag
= ttyname2dev(ttname
, &xflg
, &what
);
327 flag
= ttyname2dev(optarg
, &xflg
, &what
);
330 if (*optarg
!= '\0') {
333 what
= KERN_PROC_UID
;
334 pw
= getpwnam(optarg
);
336 flag
= parsenum(optarg
, "user name");
358 termwidth
= UNLIMITED
;
359 else if (termwidth
< 131)
373 #define BACKWARD_COMPATIBILITY
374 #ifdef BACKWARD_COMPATIBILITY
386 kd
= kvm_openfiles(NULL
, NULL
, NULL
, KVM_NO_FILES
, errbuf
);
389 kd
= kvm_openfiles(nlistf
, memf
, swapf
, O_RDONLY
, errbuf
);
392 errx(1, "%s", errbuf
);
395 parsefmt(default_fmt
);
397 /* Add default sort criteria */
398 parsesort("tdev,pid");
399 SIMPLEQ_FOREACH(vent
, &sortlist
, next
) {
400 if (vent
->var
->flag
& LWP
|| vent
->var
->type
== UNSPECIFIED
)
401 warnx("Cannot sort on %s, sort key ignored",
406 * scan requested variables, noting what structures are needed.
413 if (!(kinfo
= getkinfo_kvm(kd
, what
, flag
, &nentries
)))
414 err(1, "%s", kvm_geterr(kd
));
422 qsort(kinfo
, nentries
, sizeof(struct kinfo_proc2
), pscomp
);
424 * For each proc, call each variable output function in
425 * "setwidth" mode to determine the widest element of
429 for (i
= 0; i
< nentries
; i
++) {
430 struct kinfo_proc2
*ki
= &kinfo
[i
];
432 if (xflg
== 0 && (ki
->p_tdev
== (uint32_t)NODEV
||
433 (ki
->p_flag
& P_CONTROLT
) == 0))
436 kl
= kvm_getlwps(kd
, ki
->p_pid
, ki
->p_paddr
,
437 sizeof(struct kinfo_lwp
), &nlwps
);
441 l
= pick_representative_lwp(ki
, kl
, nlwps
);
442 SIMPLEQ_FOREACH(vent
, &displaylist
, next
)
443 OUTPUT(vent
, ki
, l
, WIDTHMODE
);
445 /* The printing is done with the loops
446 * reversed, but here we don't need that,
447 * and this improves the code locality a bit.
449 SIMPLEQ_FOREACH(vent
, &displaylist
, next
)
450 for (j
= 0; j
< nlwps
; j
++)
451 OUTPUT(vent
, ki
, &kl
[j
], WIDTHMODE
);
455 * Print header - AFTER determining process field widths.
456 * printheader() also adds up the total width of all
457 * fields the first time it's called.
461 * For each proc, call each variable output function in
464 for (i
= lineno
= 0; i
< nentries
; i
++) {
465 struct kinfo_proc2
*ki
= &kinfo
[i
];
467 if (xflg
== 0 && (ki
->p_tdev
== (uint32_t)NODEV
||
468 (ki
->p_flag
& P_CONTROLT
) == 0))
470 kl
= kvm_getlwps(kd
, ki
->p_pid
, (u_long
)ki
->p_paddr
,
471 sizeof(struct kinfo_lwp
), &nlwps
);
475 l
= pick_representative_lwp(ki
, kl
, nlwps
);
476 SIMPLEQ_FOREACH(vent
, &displaylist
, next
) {
477 OUTPUT(vent
, ki
, l
, PRINTMODE
);
478 if (SIMPLEQ_NEXT(vent
, next
) != NULL
)
482 if (prtheader
&& lineno
++ == prtheader
- 4) {
488 for (j
= 0; j
< nlwps
; j
++) {
489 SIMPLEQ_FOREACH(vent
, &displaylist
, next
) {
490 OUTPUT(vent
, ki
, &kl
[j
], PRINTMODE
);
491 if (SIMPLEQ_NEXT(vent
, next
) != NULL
)
495 if (prtheader
&& lineno
++ == prtheader
- 4) {
507 static struct kinfo_lwp
*
508 pick_representative_lwp(struct kinfo_proc2
*ki
, struct kinfo_lwp
*kl
, int nlwps
)
510 int i
, onproc
, running
, sleeping
, stopped
, suspended
;
511 static struct kinfo_lwp zero_lwp
;
516 /* Trivial case: only one LWP */
520 switch (ki
->p_realstat
) {
523 /* Pick the most live LWP */
524 onproc
= running
= sleeping
= stopped
= suspended
= -1;
525 for (i
= 0; i
< nlwps
; i
++) {
526 switch (kl
[i
].l_stat
) {
549 return &kl
[sleeping
];
553 return &kl
[suspended
];
560 /* Error condition! */
561 warnx("Inconsistent LWP state for process %d", ki
->p_pid
);
566 static struct kinfo_proc2
*
567 getkinfo_kvm(kvm_t
*kdp
, int what
, int flag
, int *nentriesp
)
570 return (kvm_getproc2(kdp
, what
, flag
, sizeof(struct kinfo_proc2
),
580 SIMPLEQ_FOREACH(vent
, &displaylist
, next
) {
582 if (v
->flag
& COMM
) {
590 pscomp(const void *a
, const void *b
)
592 const struct kinfo_proc2
*ka
= (const struct kinfo_proc2
*)a
;
593 const struct kinfo_proc2
*kb
= (const struct kinfo_proc2
*)b
;
599 const sigset_t
*sa
, *sb
;
601 #define V_SIZE(k) ((k)->p_vm_msize)
602 #define RDIFF_N(t, n) \
603 if (((const t *)((const char *)ka + v->off))[n] > ((const t *)((const char *)kb + v->off))[n]) \
605 if (((const t *)((const char *)ka + v->off))[n] < ((const t *)((const char *)kb + v->off))[n]) \
608 #define RDIFF(type) RDIFF_N(type, 0); continue
610 SIMPLEQ_FOREACH(ve
, &sortlist
, next
) {
613 /* LWP structure not available (yet) */
615 /* Sort on pvar() fields, + a few others */
638 sa
= (const void *)((const char *)a
+ v
->off
);
639 sb
= (const void *)((const char *)b
+ v
->off
);
642 if (sa
->__bits
[i
] > sb
->__bits
[i
])
644 if (sa
->__bits
[i
] < sb
->__bits
[i
])
647 } while (i
< (int)__arraycount(sa
->__bits
));
656 /* compare xxx_sec then xxx_usec */
657 RDIFF_N(uint32_t, 0);
658 RDIFF_N(uint32_t, 1);
661 i64
= ka
->p_rtime_sec
* 1000000 + ka
->p_rtime_usec
;
662 i64
-= kb
->p_rtime_sec
* 1000000 + kb
->p_rtime_usec
;
664 i64
+= ka
->p_uctime_sec
* 1000000
666 i64
-= kb
->p_uctime_sec
* 1000000
670 return i64
> 0 ? 1 : -1;
673 i
= getpcpu(kb
) - getpcpu(ka
);
678 i
= V_SIZE(kb
) - V_SIZE(ka
);
684 /* Ignore everything else */
694 * ICK (all for getopt), would rather hide the ugliness
695 * here than taint the main code.
700 * The old convention that 't' with no trailing tty arg means the user's
701 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
702 * feature is available with the option 'T', which takes no argument.
705 kludge_oldps_options(char *s
)
708 char *newopts
, *ns
, *cp
;
711 if ((newopts
= ns
= malloc(len
+ 3)) == NULL
)
714 * options begin with '-'
717 *ns
++ = '-'; /* add option flag */
719 * gaze to end of argv[1]
723 * if the last letter is a 't' flag and there are no other option
724 * characters that take arguments (eg U, p, o) in the option
725 * string and the option string doesn't start with a '-' then
726 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
728 if (*cp
== 't' && *s
!= '-' && strpbrk(s
, ARGOPTS
) == NULL
)
732 * otherwise check for trailing number, which *may* be a
735 while (cp
>= s
&& isdigit((unsigned char)*cp
))
739 memmove(ns
, s
, (size_t)(cp
- s
)); /* copy up to trailing number */
742 * if there's a trailing number, and not a preceding 'p' (pid) or
743 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
745 if (isdigit((unsigned char)*cp
) &&
746 (cp
== s
|| (cp
[-1] != 'U' && cp
[-1] != 't' && cp
[-1] != 'p' &&
747 cp
[-1] != '/' && (cp
- 1 == s
|| cp
[-2] != 't'))))
749 /* and append the number */
750 (void)strcpy(ns
, cp
); /* XXX strcpy is safe here */
756 parsenum(const char *str
, const char *msg
)
761 ul
= strtoul(str
, &ep
, 0);
763 if (*str
== '\0' || *ep
!= '\0')
764 errx(1, "Invalid %s: `%s'", msg
, str
);
767 errx(1, "Out of range %s: `%s'", msg
, str
);
776 (void)fprintf(stderr
,
777 "usage:\t%s\n\t %s\n\t%s\n",
778 "ps [-AaCcehjlmrSsTuvwx] [-k key] [-M core] [-N system] [-O fmt]",
779 "[-o fmt] [-p pid] [-t tty] [-U user] [-W swap]",