Home | History | Annotate | Line # | Download | only in ps
ps.c revision 1.50
      1 /*	$NetBSD: ps.c,v 1.50 2003/08/07 09:05:24 agc 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. Neither the name of the University nor the names of its contributors
     52  *    may be used to endorse or promote products derived from this software
     53  *    without specific prior written permission.
     54  *
     55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     65  * SUCH DAMAGE.
     66  */
     67 
     68 #include <sys/cdefs.h>
     69 #ifndef lint
     70 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\n\
     71 	The Regents of the University of California.  All rights reserved.\n");
     72 #endif /* not lint */
     73 
     74 #ifndef lint
     75 #if 0
     76 static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
     77 #else
     78 __RCSID("$NetBSD: ps.c,v 1.50 2003/08/07 09:05:24 agc Exp $");
     79 #endif
     80 #endif /* not lint */
     81 
     82 #include <sys/param.h>
     83 #include <sys/user.h>
     84 #include <sys/time.h>
     85 #include <sys/resource.h>
     86 #include <sys/lwp.h>
     87 #include <sys/proc.h>
     88 #include <sys/stat.h>
     89 #include <sys/ioctl.h>
     90 #include <sys/sysctl.h>
     91 
     92 #include <stddef.h>
     93 #include <ctype.h>
     94 #include <err.h>
     95 #include <errno.h>
     96 #include <fcntl.h>
     97 #include <kvm.h>
     98 #include <limits.h>
     99 #include <nlist.h>
    100 #include <paths.h>
    101 #include <pwd.h>
    102 #include <stdio.h>
    103 #include <stdlib.h>
    104 #include <string.h>
    105 #include <unistd.h>
    106 
    107 #include "ps.h"
    108 
    109 /*
    110  * ARGOPTS must contain all option characters that take arguments
    111  * (except for 't'!) - it is used in kludge_oldps_options()
    112  */
    113 #define	GETOPTSTR	"acCeghjk:LlM:mN:O:o:p:rSsTt:U:uvW:wx"
    114 #define	ARGOPTS		"kMNOopUW"
    115 
    116 struct kinfo_proc2 *kinfo;
    117 struct varent *vhead, *sorthead;
    118 
    119 int	eval;			/* exit value */
    120 int	rawcpu;			/* -C */
    121 int	sumrusage;		/* -S */
    122 int	termwidth;		/* width of screen (0 == infinity) */
    123 int	totwidth;		/* calculated width of requested variables */
    124 
    125 int	needcomm, needenv, commandonly;
    126 uid_t	myuid;
    127 
    128 static struct kinfo_lwp
    129 		*pick_representative_lwp __P((struct kinfo_proc2 *,
    130 		    struct kinfo_lwp *, int));
    131 static struct kinfo_proc2
    132 		*getkinfo_kvm __P((kvm_t *, int, int, int *));
    133 static char	*kludge_oldps_options __P((char *));
    134 static int	 pscomp __P((const void *, const void *));
    135 static void	 scanvars __P((void));
    136 static void	 usage __P((void));
    137 int		 main __P((int, char *[]));
    138 
    139 char dfmt[] = "pid tt state time command";
    140 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
    141 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
    142 char   o1[] = "pid";
    143 char   o2[] = "tt state time command";
    144 char sfmt[] = "uid pid ppid cpu lid nlwp pri nice vsz rss wchan lstate tt time command";
    145 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
    146 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
    147 
    148 kvm_t *kd;
    149 
    150 int
    151 main(argc, argv)
    152 	int argc;
    153 	char *argv[];
    154 {
    155 	struct varent *vent;
    156 	struct winsize ws;
    157 	struct kinfo_lwp *kl, *l;
    158 	int ch, flag, i, j, fmt, lineno, nentries, nlwps;
    159 	int prtheader, wflag, what, xflg, mode, showlwps;
    160 	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
    161 	char *ttname;
    162 
    163 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    164 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    165 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
    166 	     ws.ws_col == 0)
    167 		termwidth = 79;
    168 	else
    169 		termwidth = ws.ws_col - 1;
    170 
    171 	if (argc > 1)
    172 		argv[1] = kludge_oldps_options(argv[1]);
    173 
    174 	fmt = prtheader = wflag = xflg = showlwps = 0;
    175 	what = KERN_PROC_UID;
    176 	flag = myuid = getuid();
    177 	memf = nlistf = swapf = NULL;
    178 	mode = PRINTMODE;
    179 	while ((ch = getopt(argc, argv, GETOPTSTR)) != -1)
    180 		switch((char)ch) {
    181 		case 'a':
    182 			what = KERN_PROC_ALL;
    183 			flag = 0;
    184 			break;
    185 		case 'c':
    186 			commandonly = 1;
    187 			break;
    188 		case 'e':			/* XXX set ufmt */
    189 			needenv = 1;
    190 			break;
    191 		case 'C':
    192 			rawcpu = 1;
    193 			break;
    194 		case 'g':
    195 			break;			/* no-op */
    196 		case 'h':
    197 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
    198 			break;
    199 		case 'j':
    200 			parsefmt(jfmt);
    201 			fmt = 1;
    202 			jfmt[0] = '\0';
    203 			break;
    204 		case 'k':
    205 			parsesort(optarg);
    206 			break;
    207 		case 'K':
    208 			break;			/* no-op - was dontuseprocfs */
    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 			parsesort("vsz");
    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 			parsesort("%cpu");
    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 			parsesort("%cpu");
    310 			fmt = 1;
    311 			ufmt[0] = '\0';
    312 			break;
    313 		case 'v':
    314 			parsefmt(vfmt);
    315 			parsesort("vsz");
    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) {
    352 		kd = kvm_openfiles(NULL, NULL, NULL, 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 	/* Add default sort criteria */
    364 	parsesort("tdev,pid");
    365 	for (vent = sorthead; vent; vent = vent->next) {
    366 		if (vent->var->flag & LWP || vent->var->type == UNSPECIFIED)
    367 			warnx("Cannot sort on %s, sort key ignored\n",
    368 				vent->var->name);
    369 	}
    370 
    371 	/*
    372 	 * scan requested variables, noting what structures are needed.
    373 	 */
    374 	scanvars();
    375 
    376 	/*
    377 	 * select procs
    378 	 */
    379 	if (!(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
    380 		err(1, "%s", kvm_geterr(kd));
    381 	if (nentries == 0) {
    382 		printheader();
    383 		exit(1);
    384 	}
    385 	/*
    386 	 * sort proc list
    387 	 */
    388 	qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
    389 	/*
    390 	 * For each proc, call each variable output function in
    391 	 * "setwidth" mode to determine the widest element of
    392 	 * the column.
    393 	 */
    394 	if (mode == PRINTMODE)
    395 		for (i = 0; i < nentries; i++) {
    396 			struct kinfo_proc2 *ki = &kinfo[i];
    397 
    398 			if (xflg == 0 && (ki->p_tdev == NODEV ||
    399 			    (ki->p_flag & P_CONTROLT) == 0))
    400 				continue;
    401 
    402 			kl = kvm_getlwps(kd, ki->p_pid, ki->p_paddr,
    403 			    sizeof(struct kinfo_lwp), &nlwps);
    404 			if (kl == 0)
    405 				nlwps = 0;
    406 			if (showlwps == 0) {
    407 				l = pick_representative_lwp(ki, kl, nlwps);
    408 				for (vent = vhead; vent; vent = vent->next)
    409 					OUTPUT(vent, ki, l, WIDTHMODE);
    410 			} else {
    411 				/* The printing is done with the loops
    412 				 * reversed, but here we don't need that,
    413 				 * and this improves the code locality a bit.
    414 				 */
    415 				for (vent = vhead; vent; vent = vent->next)
    416 					for (j = 0; j < nlwps; j++)
    417 						OUTPUT(vent, ki, &kl[j],
    418 						    WIDTHMODE);
    419 			}
    420 		}
    421 	/*
    422 	 * Print header - AFTER determining process field widths.
    423 	 * printheader() also adds up the total width of all
    424 	 * fields the first time it's called.
    425 	 */
    426 	printheader();
    427 	/*
    428 	 * For each proc, call each variable output function in
    429 	 * print mode.
    430 	 */
    431 	for (i = lineno = 0; i < nentries; i++) {
    432 		struct kinfo_proc2 *ki = &kinfo[i];
    433 
    434 		if (xflg == 0 && (ki->p_tdev == NODEV ||
    435 		    (ki->p_flag & P_CONTROLT ) == 0))
    436 			continue;
    437 		kl = kvm_getlwps(kd, ki->p_pid, (u_long)ki->p_paddr,
    438 		    sizeof(struct kinfo_lwp), &nlwps);
    439 		if (kl == 0)
    440 			nlwps = 0;
    441 		if (showlwps == 0) {
    442 			l = pick_representative_lwp(ki, kl, nlwps);
    443 			for (vent = vhead; vent; vent = vent->next) {
    444 				OUTPUT(vent, ki, l, mode);
    445 				if (vent->next != NULL)
    446 					(void)putchar(' ');
    447 			}
    448 			(void)putchar('\n');
    449 			if (prtheader && lineno++ == prtheader - 4) {
    450 				(void)putchar('\n');
    451 				printheader();
    452 				lineno = 0;
    453 			}
    454 		} else {
    455 			for (j = 0; j < nlwps; j++) {
    456 				for (vent = vhead; vent; vent = vent->next) {
    457 					OUTPUT(vent, ki, &kl[j], mode);
    458 					if (vent->next != NULL)
    459 						(void)putchar(' ');
    460 				}
    461 				(void)putchar('\n');
    462 				if (prtheader && lineno++ == prtheader - 4) {
    463 					(void)putchar('\n');
    464 					printheader();
    465 					lineno = 0;
    466 				}
    467 			}
    468 		}
    469 	}
    470 	exit(eval);
    471 	/* NOTREACHED */
    472 }
    473 
    474 static struct kinfo_lwp *
    475 pick_representative_lwp(ki, kl, nlwps)
    476 	struct kinfo_proc2 *ki;
    477 	struct kinfo_lwp *kl;
    478 	int nlwps;
    479 {
    480 	int i, onproc, running, sleeping, stopped, suspended;
    481 	static struct kinfo_lwp zero_lwp;
    482 
    483 	if (kl == 0)
    484 		return &zero_lwp;
    485 
    486 	/* Trivial case: only one LWP */
    487 	if (nlwps == 1)
    488 		return kl;
    489 
    490 	switch (ki->p_realstat) {
    491 	case SSTOP:
    492 	case SACTIVE:
    493 		/* Pick the most live LWP */
    494 		onproc = running = sleeping = stopped = suspended = -1;
    495 		for (i = 0; i < nlwps; i++) {
    496 			switch (kl[i].l_stat) {
    497 			case LSONPROC:
    498 				onproc = i;
    499 				break;
    500 			case LSRUN:
    501 				running = i;
    502 				break;
    503 			case LSSLEEP:
    504 				sleeping = i;
    505 				break;
    506 			case LSSTOP:
    507 				stopped = i;
    508 				break;
    509 			case LSSUSPENDED:
    510 				suspended = i;
    511 				break;
    512 			}
    513 		}
    514 		if (onproc != -1)
    515 			return &kl[onproc];
    516 		if (running != -1)
    517 			return &kl[running];
    518 		if (sleeping != -1)
    519 			return &kl[sleeping];
    520 		if (stopped != -1)
    521 			return &kl[stopped];
    522 		if (suspended != -1)
    523 			return &kl[suspended];
    524 		break;
    525 	case SDEAD:
    526 	case SZOMB:
    527 		/* First will do */
    528 		return kl;
    529 		break;
    530 	}
    531 	/* Error condition! */
    532 	warnx("Inconsistent LWP state for process %d\n", ki->p_pid);
    533 	return kl;
    534 }
    535 
    536 
    537 static struct kinfo_proc2 *
    538 getkinfo_kvm(kdp, what, flag, nentriesp)
    539 	kvm_t *kdp;
    540 	int what, flag, *nentriesp;
    541 {
    542 	return (kvm_getproc2(kdp, what, flag, sizeof(struct kinfo_proc2),
    543 	    nentriesp));
    544 }
    545 
    546 static void
    547 scanvars()
    548 {
    549 	struct varent *vent;
    550 	VAR *v;
    551 
    552 	for (vent = vhead; vent; vent = vent->next) {
    553 		v = vent->var;
    554 		if (v->flag & COMM) {
    555 			needcomm = 1;
    556 			break;
    557 		}
    558 	}
    559 }
    560 
    561 static int
    562 pscomp(const void *a, const void *b)
    563 {
    564 	struct kinfo_proc2 *ka = (struct kinfo_proc2 *)a;
    565 	struct kinfo_proc2 *kb = (struct kinfo_proc2 *)b;
    566 
    567 	int i;
    568 	int64_t i64;
    569 	VAR *v;
    570 	struct varent *ve;
    571 	sigset_t *sa, *sb;
    572 
    573 #define V_SIZE(k) (k->p_vm_dsize + k->p_vm_ssize + k->p_vm_tsize)
    574 #define RDIFF_N(t, n) \
    575 	if (((t *)((char *)ka + v->off))[n] > ((t *)((char *)kb + v->off))[n]) \
    576 		return 1; \
    577 	if (((t *)((char *)ka + v->off))[n] < ((t *)((char *)kb + v->off))[n]) \
    578 		return -1;
    579 
    580 #define RDIFF(type) RDIFF_N(type, 0); continue
    581 
    582 	for (ve = sorthead; ve != NULL; ve = ve->next) {
    583 		v = ve->var;
    584 		if (v->flag & LWP)
    585 			/* LWP structure not available (yet) */
    586 			continue;
    587 		/* Sort on pvar() fields, + a few others */
    588 		switch (v->type) {
    589 		case CHAR:
    590 			RDIFF(char);
    591 		case UCHAR:
    592 			RDIFF(u_char);
    593 		case SHORT:
    594 			RDIFF(short);
    595 		case USHORT:
    596 			RDIFF(ushort);
    597 		case INT:
    598 			RDIFF(int);
    599 		case UINT:
    600 			RDIFF(uint);
    601 		case LONG:
    602 			RDIFF(long);
    603 		case ULONG:
    604 			RDIFF(ulong);
    605 		case INT32:
    606 			RDIFF(int32_t);
    607 		case UINT32:
    608 			RDIFF(uint32_t);
    609 		case SIGLIST:
    610 			sa = (void *)((char *)a + v->off);
    611 			sb = (void *)((char *)b + v->off);
    612 			i = 0;
    613 			do {
    614 				if (sa->__bits[i] > sb->__bits[i])
    615 					return 1;
    616 				if (sa->__bits[i] < sb->__bits[i])
    617 					return -1;
    618 				i++;
    619 			} while (i < sizeof sa->__bits / sizeof sa->__bits[0]);
    620 			continue;
    621 		case INT64:
    622 			RDIFF(int64_t);
    623 		case KPTR:
    624 		case KPTR24:
    625 		case UINT64:
    626 			RDIFF(uint64_t);
    627 		case TIMEVAL:
    628 			/* compare xxx_sec then xxx_usec */
    629 			RDIFF_N(uint32_t, 0);
    630 			RDIFF_N(uint32_t, 1);
    631 			continue;
    632 		case CPUTIME:
    633 			i64 = ka->p_rtime_sec * 1000000 + ka->p_rtime_usec;
    634 			i64 -= kb->p_rtime_sec * 1000000 + kb->p_rtime_usec;
    635 			if (sumrusage) {
    636 				i64 += ka->p_uctime_sec * 1000000
    637 				    + ka->p_uctime_usec;
    638 				i64 -= kb->p_uctime_sec * 1000000
    639 				    + kb->p_uctime_usec;
    640 			}
    641 			if (i64 != 0)
    642 				return i64 > 0 ? 1 : -1;
    643 			continue;
    644 		case PCPU:
    645 			i = getpcpu(kb) - getpcpu(ka);
    646 			if (i != 0)
    647 				return i;
    648 			continue;
    649 		case VSIZE:
    650 			i = V_SIZE(kb) - V_SIZE(ka);
    651 			if (i != 0)
    652 				return i;
    653 			continue;
    654 
    655 		default:
    656 			/* Ignore everything else */
    657 			break;
    658 		}
    659 	}
    660 	return 0;
    661 
    662 #undef VSIZE
    663 }
    664 
    665 /*
    666  * ICK (all for getopt), would rather hide the ugliness
    667  * here than taint the main code.
    668  *
    669  *  ps foo -> ps -foo
    670  *  ps 34 -> ps -p34
    671  *
    672  * The old convention that 't' with no trailing tty arg means the user's
    673  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
    674  * feature is available with the option 'T', which takes no argument.
    675  */
    676 static char *
    677 kludge_oldps_options(s)
    678 	char *s;
    679 {
    680 	size_t len;
    681 	char *newopts, *ns, *cp;
    682 
    683 	len = strlen(s);
    684 	if ((newopts = ns = malloc(len + 3)) == NULL)
    685 		err(1, NULL);
    686 	/*
    687 	 * options begin with '-'
    688 	 */
    689 	if (*s != '-')
    690 		*ns++ = '-';	/* add option flag */
    691 	/*
    692 	 * gaze to end of argv[1]
    693 	 */
    694 	cp = s + len - 1;
    695 	/*
    696 	 * if the last letter is a 't' flag and there are no other option
    697 	 * characters that take arguments (eg U, p, o) in the option
    698 	 * string and the option string doesn't start with a '-' then
    699 	 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
    700 	 */
    701 	if (*cp == 't' && *s != '-' && strpbrk(s, ARGOPTS) == NULL)
    702 		*cp = 'T';
    703 	else {
    704 		/*
    705 		 * otherwise check for trailing number, which *may* be a
    706 		 * pid.
    707 		 */
    708 		while (cp >= s && isdigit(*cp))
    709 			--cp;
    710 	}
    711 	cp++;
    712 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
    713 	ns += cp - s;
    714 	/*
    715 	 * if there's a trailing number, and not a preceding 'p' (pid) or
    716 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
    717 	 */
    718 	if (isdigit(*cp) &&
    719 	    (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
    720 	     (cp - 1 == s || cp[-2] != 't'))))
    721 		*ns++ = 'p';
    722 	/* and append the number */
    723 	(void)strcpy(ns, cp);		/* XXX strcpy is safe here */
    724 
    725 	return (newopts);
    726 }
    727 
    728 static void
    729 usage()
    730 {
    731 
    732 	(void)fprintf(stderr,
    733 	    "usage:\t%s\n\t   %s\n\t%s\n",
    734 	    "ps [-acCehjlmrsSTuvwx] [-k key] [-O|o fmt] [-p pid] [-t tty]",
    735 	    "[-M core] [-N system] [-W swap] [-U username]",
    736 	    "ps [-L]");
    737 	exit(1);
    738 	/* NOTREACHED */
    739 }
    740