ps.c revision 1.46.2.2 1 /* $NetBSD: ps.c,v 1.46.2.2 2002/04/23 20:41:14 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.2 2002/04/23 20:41:14 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 state 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 'L':
210 showkey();
211 exit(0);
212 /* NOTREACHED */
213 case 'l':
214 parsefmt(lfmt);
215 fmt = 1;
216 lfmt[0] = '\0';
217 break;
218 case 'M':
219 memf = optarg;
220 break;
221 case 'm':
222 sortby = SORTMEM;
223 break;
224 case 'N':
225 nlistf = optarg;
226 break;
227 case 'O':
228 parsefmt(o1);
229 parsefmt(optarg);
230 parsefmt(o2);
231 o1[0] = o2[0] = '\0';
232 fmt = 1;
233 break;
234 case 'o':
235 parsefmt(optarg);
236 fmt = 1;
237 break;
238 case 'p':
239 what = KERN_PROC_PID;
240 flag = atol(optarg);
241 xflg = 1;
242 break;
243 case 'r':
244 sortby = SORTCPU;
245 break;
246 case 'S':
247 sumrusage = 1;
248 break;
249 case 's':
250 /* -L was already taken... */
251 showlwps = 1;
252 parsefmt(sfmt);
253 fmt = 1;
254 sfmt[0] = '\0';
255 break;
256 case 'T':
257 if ((ttname = ttyname(STDIN_FILENO)) == NULL)
258 errx(1, "stdin: not a terminal");
259 goto tty;
260 case 't':
261 ttname = optarg;
262 tty: {
263 struct stat sb;
264 char *ttypath, pathbuf[MAXPATHLEN];
265
266 flag = 0;
267 if (strcmp(ttname, "?") == 0)
268 flag = KERN_PROC_TTY_NODEV;
269 else if (strcmp(ttname, "-") == 0)
270 flag = KERN_PROC_TTY_REVOKE;
271 else if (strcmp(ttname, "co") == 0)
272 ttypath = _PATH_CONSOLE;
273 else if (*ttname != '/')
274 (void)snprintf(ttypath = pathbuf,
275 sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
276 else
277 ttypath = ttname;
278 what = KERN_PROC_TTY;
279 if (flag == 0) {
280 if (stat(ttypath, &sb) == -1)
281 err(1, "%s", ttypath);
282 if (!S_ISCHR(sb.st_mode))
283 errx(1, "%s: not a terminal", ttypath);
284 flag = sb.st_rdev;
285 }
286 break;
287 }
288 case 'U':
289 if (*optarg != '\0') {
290 struct passwd *pw;
291 char *ep;
292
293 what = KERN_PROC_UID;
294 pw = getpwnam(optarg);
295 if (pw == NULL) {
296 errno = 0;
297 flag = strtoul(optarg, &ep, 10);
298 if (errno)
299 err(1, "%s", optarg);
300 if (*ep != '\0')
301 errx(1, "%s: illegal user name",
302 optarg);
303 } else
304 flag = pw->pw_uid;
305 }
306 break;
307 case 'u':
308 parsefmt(ufmt);
309 sortby = SORTCPU;
310 fmt = 1;
311 ufmt[0] = '\0';
312 break;
313 case 'v':
314 parsefmt(vfmt);
315 sortby = SORTMEM;
316 fmt = 1;
317 vfmt[0] = '\0';
318 break;
319 case 'W':
320 swapf = optarg;
321 break;
322 case 'w':
323 if (wflag)
324 termwidth = UNLIMITED;
325 else if (termwidth < 131)
326 termwidth = 131;
327 wflag++;
328 break;
329 case 'x':
330 xflg = 1;
331 break;
332 case '?':
333 default:
334 usage();
335 }
336 argc -= optind;
337 argv += optind;
338
339 #define BACKWARD_COMPATIBILITY
340 #ifdef BACKWARD_COMPATIBILITY
341 if (*argv) {
342 nlistf = *argv;
343 if (*++argv) {
344 memf = *argv;
345 if (*++argv)
346 swapf = *argv;
347 }
348 }
349 #endif
350
351 if (memf == NULL && swapf == NULL) {
352 kd = kvm_openfiles(nlistf, memf, swapf, KVM_NO_FILES, errbuf);
353 donlist_sysctl();
354 } else
355 kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
356
357 if (kd == 0)
358 errx(1, "%s", errbuf);
359
360 if (!fmt)
361 parsefmt(dfmt);
362
363 /*
364 * scan requested variables, noting what structures are needed.
365 */
366 scanvars();
367
368 /*
369 * select procs
370 */
371 if (!(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
372 err(1, "%s.", kvm_geterr(kd));
373
374 if (nentries == 0) {
375 printheader();
376 exit(1);
377 }
378 /*
379 * sort proc list
380 */
381 qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
382 /*
383 * For each proc, call each variable output function in
384 * "setwidth" mode to determine the widest element of
385 * the column.
386 */
387 if (mode == PRINTMODE)
388 for (i = 0; i < nentries; i++) {
389 struct kinfo_proc2 *ki = &kinfo[i];
390
391 if (xflg == 0 && (ki->p_tdev == NODEV ||
392 (ki->p_flag & P_CONTROLT) == 0))
393 continue;
394
395 kl = kvm_getlwps(kd, ki->p_pid, ki->p_paddr,
396 sizeof(struct kinfo_lwp), &nlwps);
397 if (showlwps == 0) {
398 l = pick_representative_lwp(ki, kl, nlwps);
399 for (vent = vhead; vent; vent = vent->next)
400 OUTPUT(vent, ki, l, WIDTHMODE);
401 } else {
402 /* The printing is done with the loops
403 * reversed, but here we don't need that,
404 * and this improves the code locality a bit.
405 */
406 for (vent = vhead; vent; vent = vent->next)
407 for (j = 0; j < nlwps; j++)
408 OUTPUT(vent, ki, &kl[j],
409 WIDTHMODE);
410 }
411 free(kl);
412 }
413 /*
414 * Print header - AFTER determining process field widths.
415 * printheader() also adds up the total width of all
416 * fields the first time it's called.
417 */
418 printheader();
419 /*
420 * For each proc, call each variable output function in
421 * print mode.
422 */
423 for (i = lineno = 0; i < nentries; i++) {
424 struct kinfo_proc2 *ki = &kinfo[i];
425
426 if (xflg == 0 && (ki->p_tdev == NODEV ||
427 (ki->p_flag & P_CONTROLT ) == 0))
428 continue;
429 kl = kvm_getlwps(kd, ki->p_pid, (u_long)ki->p_paddr,
430 sizeof(struct kinfo_lwp), &nlwps);
431
432 if (showlwps == 0) {
433 l = pick_representative_lwp(ki, kl, nlwps);
434 for (vent = vhead; vent; vent = vent->next) {
435 OUTPUT(vent, ki, l, mode);
436 if (vent->next != NULL)
437 (void)putchar(' ');
438 }
439 (void)putchar('\n');
440 if (prtheader && lineno++ == prtheader - 4) {
441 (void)putchar('\n');
442 printheader();
443 lineno = 0;
444 }
445 } else {
446 for (j = 0; j < nlwps; j++) {
447 for (vent = vhead; vent; vent = vent->next) {
448 OUTPUT(vent, ki, &kl[j], mode);
449 if (vent->next != NULL)
450 (void)putchar(' ');
451 }
452 (void)putchar('\n');
453 if (prtheader && lineno++ == prtheader - 4) {
454 (void)putchar('\n');
455 printheader();
456 lineno = 0;
457 }
458 }
459 }
460 free(kl);
461 }
462 exit(eval);
463 /* NOTREACHED */
464 }
465
466 static struct kinfo_lwp *
467 pick_representative_lwp(ki, kl, nlwps)
468 struct kinfo_proc2 *ki;
469 struct kinfo_lwp *kl;
470 int nlwps;
471 {
472 int i, onproc, run, sleep;
473
474 /* Trivial case: only one LWP */
475 if (nlwps == 1)
476 return kl;
477
478 switch (ki->p_stat) {
479 case SSTOP:
480 /* Pick the first stopped LWP */
481 for (i = 0; i < nlwps; i++) {
482 if (kl[i].l_stat == LSSTOP)
483 return &kl[i];
484 }
485 break;
486 case SACTIVE:
487 /* Pick the most live LWP */
488 onproc = run = sleep = 0;
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 run = i;
496 break;
497 case LSSLEEP:
498 sleep = i;
499 break;
500 }
501 }
502 if (onproc)
503 return &kl[onproc];
504 if (run)
505 return &kl[run];
506 if (sleep)
507 return &kl[sleep];
508 break;
509 case SDEAD:
510 case SZOMB:
511 /* First will do */
512 return kl;
513 break;
514 }
515 /* Error condition! */
516 warnx("Inconsistent LWP state for process %d\n", ki->p_pid);
517 return kl;
518 }
519
520
521 static struct kinfo_proc2 *
522 getkinfo_kvm(kdp, what, flag, nentriesp)
523 kvm_t *kdp;
524 int what, flag, *nentriesp;
525 {
526 return (kvm_getproc2(kdp, what, flag, sizeof(struct kinfo_proc2),
527 nentriesp));
528 }
529
530 static void
531 scanvars()
532 {
533 struct varent *vent;
534 VAR *v;
535
536 for (vent = vhead; vent; vent = vent->next) {
537 v = vent->var;
538 if (v->flag & COMM) {
539 needcomm = 1;
540 break;
541 }
542 }
543 }
544
545 static int
546 pscomp(a, b)
547 const void *a, *b;
548 {
549 struct kinfo_proc2 *ka = (struct kinfo_proc2 *)a;
550 struct kinfo_proc2 *kb = (struct kinfo_proc2 *)b;
551
552 int i;
553 #define VSIZE(k) (k->p_vm_dsize + k->p_vm_ssize + k->p_vm_tsize)
554
555 if (sortby == SORTCPU)
556 return (getpcpu(kb) - getpcpu(ka));
557 if (sortby == SORTMEM)
558 return (VSIZE(kb) - VSIZE(ka));
559 i = ka->p_tdev - kb->p_tdev;
560
561 if (i == 0)
562 i = ka->p_pid - kb->p_pid;
563 return (i);
564 }
565
566 /*
567 * ICK (all for getopt), would rather hide the ugliness
568 * here than taint the main code.
569 *
570 * ps foo -> ps -foo
571 * ps 34 -> ps -p34
572 *
573 * The old convention that 't' with no trailing tty arg means the user's
574 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
575 * feature is available with the option 'T', which takes no argument.
576 */
577 static char *
578 kludge_oldps_options(s)
579 char *s;
580 {
581 size_t len;
582 char *newopts, *ns, *cp;
583
584 len = strlen(s);
585 if ((newopts = ns = malloc(len + 3)) == NULL)
586 err(1, NULL);
587 /*
588 * options begin with '-'
589 */
590 if (*s != '-')
591 *ns++ = '-'; /* add option flag */
592 /*
593 * gaze to end of argv[1]
594 */
595 cp = s + len - 1;
596 /*
597 * if the last letter is a 't' flag and there are no other option
598 * characters that take arguments (eg U, p, o) in the option
599 * string and the option string doesn't start with a '-' then
600 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
601 */
602 if (*cp == 't' && *s != '-' && strpbrk(s, ARGOPTS) == NULL)
603 *cp = 'T';
604 else {
605 /*
606 * otherwise check for trailing number, which *may* be a
607 * pid.
608 */
609 while (cp >= s && isdigit(*cp))
610 --cp;
611 }
612 cp++;
613 memmove(ns, s, (size_t)(cp - s)); /* copy up to trailing number */
614 ns += cp - s;
615 /*
616 * if there's a trailing number, and not a preceding 'p' (pid) or
617 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
618 */
619 if (isdigit(*cp) &&
620 (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
621 (cp - 1 == s || cp[-2] != 't'))))
622 *ns++ = 'p';
623 /* and append the number */
624 (void)strcpy(ns, cp); /* XXX strcpy is safe here */
625
626 return (newopts);
627 }
628
629 static void
630 usage()
631 {
632
633 (void)fprintf(stderr,
634 "usage:\t%s\n\t %s\n\t%s\n",
635 "ps [-acCehjKlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
636 "[-M core] [-N system] [-W swap] [-U username]",
637 "ps [-L]");
638 exit(1);
639 /* NOTREACHED */
640 }
641