ps.c revision 1.46.2.11 1 /* $NetBSD: ps.c,v 1.46.2.11 2002/11/12 20:31:58 nathanw Exp $ */
2
3 /*
4 * Copyright (c) 2000 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Simon Burge.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 /*
40 * Copyright (c) 1990, 1993, 1994
41 * The Regents of the University of California. All rights reserved.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
70 */
71
72 #include <sys/cdefs.h>
73 #ifndef lint
74 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\n\
75 The Regents of the University of California. All rights reserved.\n");
76 #endif /* not lint */
77
78 #ifndef lint
79 #if 0
80 static char sccsid[] = "@(#)ps.c 8.4 (Berkeley) 4/2/94";
81 #else
82 __RCSID("$NetBSD: ps.c,v 1.46.2.11 2002/11/12 20:31:58 nathanw Exp $");
83 #endif
84 #endif /* not lint */
85
86 #include <sys/param.h>
87 #include <sys/user.h>
88 #include <sys/time.h>
89 #include <sys/resource.h>
90 #include <sys/lwp.h>
91 #include <sys/proc.h>
92 #include <sys/stat.h>
93 #include <sys/ioctl.h>
94 #include <sys/sysctl.h>
95
96 #include <ctype.h>
97 #include <err.h>
98 #include <errno.h>
99 #include <fcntl.h>
100 #include <kvm.h>
101 #include <limits.h>
102 #include <nlist.h>
103 #include <paths.h>
104 #include <pwd.h>
105 #include <stdio.h>
106 #include <stdlib.h>
107 #include <string.h>
108 #include <unistd.h>
109
110 #include "ps.h"
111
112 /*
113 * ARGOPTS must contain all option characters that take arguments
114 * (except for 't'!) - it is used in kludge_oldps_options()
115 */
116 #define GETOPTSTR "acCeghjLlM:mN:O:o:p:rSsTt:U:uvW:wx"
117 #define ARGOPTS "MNOopUW"
118
119 struct kinfo_proc2 *kinfo;
120 struct varent *vhead, *vtail;
121
122 int eval; /* exit value */
123 int rawcpu; /* -C */
124 int sumrusage; /* -S */
125 int termwidth; /* width of screen (0 == infinity) */
126 int totwidth; /* calculated width of requested variables */
127
128 int needcomm, needenv, commandonly;
129 uid_t myuid;
130
131 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
132
133 static struct kinfo_lwp
134 *pick_representative_lwp __P((struct kinfo_proc2 *,
135 struct kinfo_lwp *, int));
136 static struct kinfo_proc2
137 *getkinfo_kvm __P((kvm_t *, int, int, int *));
138 static char *kludge_oldps_options __P((char *));
139 static int pscomp __P((const void *, const void *));
140 static void scanvars __P((void));
141 static void usage __P((void));
142 int main __P((int, char *[]));
143
144 char dfmt[] = "pid tt state time command";
145 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
146 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
147 char o1[] = "pid";
148 char o2[] = "tt state time command";
149 char sfmt[] = "uid pid ppid cpu lid nlwp pri nice vsz rss wchan lstate tt time command";
150 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
151 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
152
153 kvm_t *kd;
154
155 int
156 main(argc, argv)
157 int argc;
158 char *argv[];
159 {
160 struct varent *vent;
161 struct winsize ws;
162 struct kinfo_lwp *kl, *l;
163 int ch, flag, i, j, fmt, lineno, nentries, nlwps;
164 int prtheader, wflag, what, xflg, mode, showlwps;
165 char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
166 char *ttname;
167
168 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
169 ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
170 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ws) == -1) ||
171 ws.ws_col == 0)
172 termwidth = 79;
173 else
174 termwidth = ws.ws_col - 1;
175
176 if (argc > 1)
177 argv[1] = kludge_oldps_options(argv[1]);
178
179 fmt = prtheader = wflag = xflg = showlwps = 0;
180 what = KERN_PROC_UID;
181 flag = myuid = getuid();
182 memf = nlistf = swapf = NULL;
183 mode = PRINTMODE;
184 while ((ch = getopt(argc, argv, GETOPTSTR)) != -1)
185 switch((char)ch) {
186 case 'a':
187 what = KERN_PROC_ALL;
188 flag = 0;
189 break;
190 case 'c':
191 commandonly = 1;
192 break;
193 case 'e': /* XXX set ufmt */
194 needenv = 1;
195 break;
196 case 'C':
197 rawcpu = 1;
198 break;
199 case 'g':
200 break; /* no-op */
201 case 'h':
202 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
203 break;
204 case 'j':
205 parsefmt(jfmt);
206 fmt = 1;
207 jfmt[0] = '\0';
208 break;
209 case 'K':
210 break; /* no-op - was dontuseprocfs */
211 case 'L':
212 showkey();
213 exit(0);
214 /* NOTREACHED */
215 case 'l':
216 parsefmt(lfmt);
217 fmt = 1;
218 lfmt[0] = '\0';
219 break;
220 case 'M':
221 memf = optarg;
222 break;
223 case 'm':
224 sortby = SORTMEM;
225 break;
226 case 'N':
227 nlistf = optarg;
228 break;
229 case 'O':
230 parsefmt(o1);
231 parsefmt(optarg);
232 parsefmt(o2);
233 o1[0] = o2[0] = '\0';
234 fmt = 1;
235 break;
236 case 'o':
237 parsefmt(optarg);
238 fmt = 1;
239 break;
240 case 'p':
241 what = KERN_PROC_PID;
242 flag = atol(optarg);
243 xflg = 1;
244 break;
245 case 'r':
246 sortby = SORTCPU;
247 break;
248 case 'S':
249 sumrusage = 1;
250 break;
251 case 's':
252 /* -L was already taken... */
253 showlwps = 1;
254 parsefmt(sfmt);
255 fmt = 1;
256 sfmt[0] = '\0';
257 break;
258 case 'T':
259 if ((ttname = ttyname(STDIN_FILENO)) == NULL)
260 errx(1, "stdin: not a terminal");
261 goto tty;
262 case 't':
263 ttname = optarg;
264 tty: {
265 struct stat sb;
266 char *ttypath, pathbuf[MAXPATHLEN];
267
268 flag = 0;
269 if (strcmp(ttname, "?") == 0)
270 flag = KERN_PROC_TTY_NODEV;
271 else if (strcmp(ttname, "-") == 0)
272 flag = KERN_PROC_TTY_REVOKE;
273 else if (strcmp(ttname, "co") == 0)
274 ttypath = _PATH_CONSOLE;
275 else if (*ttname != '/')
276 (void)snprintf(ttypath = pathbuf,
277 sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
278 else
279 ttypath = ttname;
280 what = KERN_PROC_TTY;
281 if (flag == 0) {
282 if (stat(ttypath, &sb) == -1)
283 err(1, "%s", ttypath);
284 if (!S_ISCHR(sb.st_mode))
285 errx(1, "%s: not a terminal", ttypath);
286 flag = sb.st_rdev;
287 }
288 break;
289 }
290 case 'U':
291 if (*optarg != '\0') {
292 struct passwd *pw;
293 char *ep;
294
295 what = KERN_PROC_UID;
296 pw = getpwnam(optarg);
297 if (pw == NULL) {
298 errno = 0;
299 flag = strtoul(optarg, &ep, 10);
300 if (errno)
301 err(1, "%s", optarg);
302 if (*ep != '\0')
303 errx(1, "%s: illegal user name",
304 optarg);
305 } else
306 flag = pw->pw_uid;
307 }
308 break;
309 case 'u':
310 parsefmt(ufmt);
311 sortby = SORTCPU;
312 fmt = 1;
313 ufmt[0] = '\0';
314 break;
315 case 'v':
316 parsefmt(vfmt);
317 sortby = SORTMEM;
318 fmt = 1;
319 vfmt[0] = '\0';
320 break;
321 case 'W':
322 swapf = optarg;
323 break;
324 case 'w':
325 if (wflag)
326 termwidth = UNLIMITED;
327 else if (termwidth < 131)
328 termwidth = 131;
329 wflag++;
330 break;
331 case 'x':
332 xflg = 1;
333 break;
334 case '?':
335 default:
336 usage();
337 }
338 argc -= optind;
339 argv += optind;
340
341 #define BACKWARD_COMPATIBILITY
342 #ifdef BACKWARD_COMPATIBILITY
343 if (*argv) {
344 nlistf = *argv;
345 if (*++argv) {
346 memf = *argv;
347 if (*++argv)
348 swapf = *argv;
349 }
350 }
351 #endif
352
353 if (memf == NULL && swapf == NULL) {
354 kd = kvm_openfiles(nlistf, memf, swapf, KVM_NO_FILES, errbuf);
355 donlist_sysctl();
356 } else
357 kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
358
359 if (kd == 0)
360 errx(1, "%s", errbuf);
361
362 if (!fmt)
363 parsefmt(dfmt);
364
365 /*
366 * scan requested variables, noting what structures are needed.
367 */
368 scanvars();
369
370 /*
371 * select procs
372 */
373 if (!(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
374 err(1, "%s", kvm_geterr(kd));
375 if (nentries == 0) {
376 printheader();
377 exit(1);
378 }
379 /*
380 * sort proc list
381 */
382 qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
383 /*
384 * For each proc, call each variable output function in
385 * "setwidth" mode to determine the widest element of
386 * the column.
387 */
388 if (mode == PRINTMODE)
389 for (i = 0; i < nentries; i++) {
390 struct kinfo_proc2 *ki = &kinfo[i];
391
392 if (xflg == 0 && (ki->p_tdev == NODEV ||
393 (ki->p_flag & P_CONTROLT) == 0))
394 continue;
395
396 kl = kvm_getlwps(kd, ki->p_pid, ki->p_paddr,
397 sizeof(struct kinfo_lwp), &nlwps);
398 if (kl == 0)
399 nlwps = 0;
400 if (showlwps == 0) {
401 l = pick_representative_lwp(ki, kl, nlwps);
402 for (vent = vhead; vent; vent = vent->next)
403 OUTPUT(vent, ki, l, WIDTHMODE);
404 } else {
405 /* The printing is done with the loops
406 * reversed, but here we don't need that,
407 * and this improves the code locality a bit.
408 */
409 for (vent = vhead; vent; vent = vent->next)
410 for (j = 0; j < nlwps; j++)
411 OUTPUT(vent, ki, &kl[j],
412 WIDTHMODE);
413 }
414 }
415 /*
416 * Print header - AFTER determining process field widths.
417 * printheader() also adds up the total width of all
418 * fields the first time it's called.
419 */
420 printheader();
421 /*
422 * For each proc, call each variable output function in
423 * print mode.
424 */
425 for (i = lineno = 0; i < nentries; i++) {
426 struct kinfo_proc2 *ki = &kinfo[i];
427
428 if (xflg == 0 && (ki->p_tdev == NODEV ||
429 (ki->p_flag & P_CONTROLT ) == 0))
430 continue;
431 kl = kvm_getlwps(kd, ki->p_pid, (u_long)ki->p_paddr,
432 sizeof(struct kinfo_lwp), &nlwps);
433 if (kl == 0)
434 nlwps = 0;
435 if (showlwps == 0) {
436 l = pick_representative_lwp(ki, kl, nlwps);
437 for (vent = vhead; vent; vent = vent->next) {
438 OUTPUT(vent, ki, l, mode);
439 if (vent->next != NULL)
440 (void)putchar(' ');
441 }
442 (void)putchar('\n');
443 if (prtheader && lineno++ == prtheader - 4) {
444 (void)putchar('\n');
445 printheader();
446 lineno = 0;
447 }
448 } else {
449 for (j = 0; j < nlwps; j++) {
450 for (vent = vhead; vent; vent = vent->next) {
451 OUTPUT(vent, ki, &kl[j], mode);
452 if (vent->next != NULL)
453 (void)putchar(' ');
454 }
455 (void)putchar('\n');
456 if (prtheader && lineno++ == prtheader - 4) {
457 (void)putchar('\n');
458 printheader();
459 lineno = 0;
460 }
461 }
462 }
463 }
464 exit(eval);
465 /* NOTREACHED */
466 }
467
468 static struct kinfo_lwp *
469 pick_representative_lwp(ki, kl, nlwps)
470 struct kinfo_proc2 *ki;
471 struct kinfo_lwp *kl;
472 int nlwps;
473 {
474 int i, onproc, running, sleeping, stopped, suspended;
475 static struct kinfo_lwp zero_lwp;
476
477 if (kl == 0)
478 return &zero_lwp;
479
480 /* Trivial case: only one LWP */
481 if (nlwps == 1)
482 return kl;
483
484 switch (ki->p_realstat) {
485 case SSTOP:
486 case SACTIVE:
487 /* Pick the most live LWP */
488 onproc = running = sleeping = stopped = suspended = -1;
489 for (i = 0; i < nlwps; i++) {
490 switch (kl[i].l_stat) {
491 case LSONPROC:
492 onproc = i;
493 break;
494 case LSRUN:
495 running = i;
496 break;
497 case LSSLEEP:
498 sleeping = i;
499 break;
500 case LSSTOP:
501 stopped = i;
502 break;
503 case LSSUSPENDED:
504 suspended = i;
505 break;
506 }
507 }
508 if (onproc != -1)
509 return &kl[onproc];
510 if (running != -1)
511 return &kl[running];
512 if (sleeping != -1)
513 return &kl[sleeping];
514 if (stopped != -1)
515 return &kl[stopped];
516 if (suspended != -1)
517 return &kl[suspended];
518 break;
519 case SDEAD:
520 case SZOMB:
521 /* First will do */
522 return kl;
523 break;
524 }
525 /* Error condition! */
526 warnx("Inconsistent LWP state for process %d\n", ki->p_pid);
527 return kl;
528 }
529
530
531 static struct kinfo_proc2 *
532 getkinfo_kvm(kdp, what, flag, nentriesp)
533 kvm_t *kdp;
534 int what, flag, *nentriesp;
535 {
536 return (kvm_getproc2(kdp, what, flag, sizeof(struct kinfo_proc2),
537 nentriesp));
538 }
539
540 static void
541 scanvars()
542 {
543 struct varent *vent;
544 VAR *v;
545
546 for (vent = vhead; vent; vent = vent->next) {
547 v = vent->var;
548 if (v->flag & COMM) {
549 needcomm = 1;
550 break;
551 }
552 }
553 }
554
555 static int
556 pscomp(a, b)
557 const void *a, *b;
558 {
559 struct kinfo_proc2 *ka = (struct kinfo_proc2 *)a;
560 struct kinfo_proc2 *kb = (struct kinfo_proc2 *)b;
561
562 int i;
563 #define VSIZE(k) (k->p_vm_dsize + k->p_vm_ssize + k->p_vm_tsize)
564
565 if (sortby == SORTCPU)
566 return (getpcpu(kb) - getpcpu(ka));
567 if (sortby == SORTMEM)
568 return (VSIZE(kb) - VSIZE(ka));
569 i = ka->p_tdev - kb->p_tdev;
570
571 if (i == 0)
572 i = ka->p_pid - kb->p_pid;
573 return (i);
574 }
575
576 /*
577 * ICK (all for getopt), would rather hide the ugliness
578 * here than taint the main code.
579 *
580 * ps foo -> ps -foo
581 * ps 34 -> ps -p34
582 *
583 * The old convention that 't' with no trailing tty arg means the user's
584 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
585 * feature is available with the option 'T', which takes no argument.
586 */
587 static char *
588 kludge_oldps_options(s)
589 char *s;
590 {
591 size_t len;
592 char *newopts, *ns, *cp;
593
594 len = strlen(s);
595 if ((newopts = ns = malloc(len + 3)) == NULL)
596 err(1, NULL);
597 /*
598 * options begin with '-'
599 */
600 if (*s != '-')
601 *ns++ = '-'; /* add option flag */
602 /*
603 * gaze to end of argv[1]
604 */
605 cp = s + len - 1;
606 /*
607 * if the last letter is a 't' flag and there are no other option
608 * characters that take arguments (eg U, p, o) in the option
609 * string and the option string doesn't start with a '-' then
610 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
611 */
612 if (*cp == 't' && *s != '-' && strpbrk(s, ARGOPTS) == NULL)
613 *cp = 'T';
614 else {
615 /*
616 * otherwise check for trailing number, which *may* be a
617 * pid.
618 */
619 while (cp >= s && isdigit(*cp))
620 --cp;
621 }
622 cp++;
623 memmove(ns, s, (size_t)(cp - s)); /* copy up to trailing number */
624 ns += cp - s;
625 /*
626 * if there's a trailing number, and not a preceding 'p' (pid) or
627 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
628 */
629 if (isdigit(*cp) &&
630 (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
631 (cp - 1 == s || cp[-2] != 't'))))
632 *ns++ = 'p';
633 /* and append the number */
634 (void)strcpy(ns, cp); /* XXX strcpy is safe here */
635
636 return (newopts);
637 }
638
639 static void
640 usage()
641 {
642
643 (void)fprintf(stderr,
644 "usage:\t%s\n\t %s\n\t%s\n",
645 "ps [-acCehjlmrsSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
646 "[-M core] [-N system] [-W swap] [-U username]",
647 "ps [-L]");
648 exit(1);
649 /* NOTREACHED */
650 }
651