Home | History | Annotate | Line # | Download | only in ps
ps.c revision 1.5
      1 /*-
      2  * Copyright (c) 1990 The Regents of the University of California.
      3  * All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  * 3. All advertising materials mentioning features or use of this software
     14  *    must display the following acknowledgement:
     15  *	This product includes software developed by the University of
     16  *	California, Berkeley and its contributors.
     17  * 4. Neither the name of the University nor the names of its contributors
     18  *    may be used to endorse or promote products derived from this software
     19  *    without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 #ifndef lint
     35 char copyright[] =
     36 "@(#) Copyright (c) 1990 The Regents of the University of California.\n\
     37  All rights reserved.\n";
     38 #endif /* not lint */
     39 
     40 #ifndef lint
     41 static char sccsid[] = "@(#)ps.c	5.43 (Berkeley) 7/1/91";
     42 static char rcsid[] = "$Header: /tank/opengrok/rsync2/NetBSD/src/bin/ps/ps.c,v 1.5 1993/06/01 01:38:32 cgd Exp $";
     43 #endif /* not lint */
     44 
     45 #include <sys/param.h>
     46 #include <sys/user.h>
     47 #include <sys/time.h>
     48 #include <sys/resource.h>
     49 #include <sys/proc.h>
     50 #include <sys/stat.h>
     51 #include <sys/ioctl.h>
     52 #include <sys/kinfo.h>
     53 #include <nlist.h>
     54 #include <kvm.h>
     55 #include <errno.h>
     56 #include <unistd.h>
     57 #include <stdio.h>
     58 #include <stdlib.h>
     59 #include <string.h>
     60 #include <paths.h>
     61 #include "ps.h"
     62 
     63 #ifdef SPPWAIT
     64 #define NEWVM
     65 #endif
     66 
     67 KINFO *kinfo;
     68 struct varent *vhead, *vtail;
     69 
     70 int	eval;			/* exit value */
     71 int	rawcpu;			/* -C */
     72 int	sumrusage;		/* -S */
     73 int	termwidth;		/* width of screen (0 == infinity) */
     74 int	totwidth;		/* calculated width of requested variables */
     75 
     76 static int needuser, needcomm, needenv;
     77 
     78 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
     79 
     80 uid_t	getuid();
     81 char	*ttyname();
     82 double	getpcpu();					/* 14 Sep 92*/
     83 
     84 char dfmt[] = "pid tt state time command";
     85 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
     86 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
     87 char   o1[] = "pid";
     88 char   o2[] = "tt state time command";
     89 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
     90 char vfmt[] =
     91 	"pid state time sl re pagein vsz rss lim tsiz trs %cpu %mem command";
     92 
     93 main(argc, argv)
     94 	int argc;
     95 	char **argv;
     96 {
     97 	extern char *optarg;
     98 	extern int optind;
     99 	register struct proc *p;
    100 	register size_t nentries;
    101 	register struct varent *vent;
    102 	register int i;
    103 	struct winsize ws;
    104 	dev_t ttydev;
    105 	int all, ch, flag, fmt, lineno, pid, prtheader, uid, what, xflg;
    106 	int pscomp();
    107 	char *nlistf, *memf, *swapf;
    108 	char *kludge_oldps_options();
    109 
    110 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    111 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    112 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
    113 	     ws.ws_col == 0)
    114 		termwidth = 79;
    115 	else
    116 		termwidth = ws.ws_col - 1;
    117 
    118 	if (argc > 1)
    119 		argv[1] = kludge_oldps_options(argv[1]);
    120 
    121 	fmt = 0;
    122 	all = xflg = 0;
    123 	pid = uid = -1;
    124 	ttydev = NODEV;
    125 	memf = nlistf = swapf = NULL;
    126 	while ((ch = getopt(argc, argv,
    127 	    "aCeghjLlM:mN:O:o:p:rSTt:uvW:wx")) != EOF)
    128 		switch((char)ch) {
    129 		case 'a':
    130 			all = 1;
    131 			break;
    132 		case 'C':
    133 			rawcpu = 1;
    134 			break;
    135 		case 'e':
    136 			needenv = 1;
    137 			break;
    138 		case 'g':
    139 			break;	/* no-op */
    140 		case 'h':
    141 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
    142 			break;
    143 		case 'j':
    144 			parsefmt(jfmt);
    145 			fmt = 1;
    146 			jfmt[0] = '\0';
    147 			break;
    148 		case 'L':
    149 			showkey();
    150 			exit(0);
    151 		case 'l':
    152 			parsefmt(lfmt);
    153 			fmt = 1;
    154 			lfmt[0] = '\0';
    155 			break;
    156 		case 'M':
    157 			memf = optarg;
    158 			break;
    159 		case 'm':
    160 			sortby = SORTMEM;
    161 			break;
    162 		case 'N':
    163 			nlistf = optarg;
    164 			break;
    165 		case 'O':
    166 			parsefmt(o1);
    167 			parsefmt(optarg);
    168 			parsefmt(o2);
    169 			o1[0] = o2[0] = '\0';
    170 			fmt = 1;
    171 			break;
    172 		case 'o':
    173 			parsefmt(optarg);
    174 			fmt = 1;
    175 			break;
    176 		case 'p':
    177 			pid = atoi(optarg);
    178 			xflg = 1;
    179 			break;
    180 		case 'r':
    181 			sortby = SORTCPU;
    182 			break;
    183 		case 'S':
    184 			sumrusage = 1;
    185 			break;
    186 		case 'T':
    187 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
    188 				err("stdin: not a terminal");
    189 			/* FALLTHROUGH */
    190 		case 't': {
    191 			char *ttypath;
    192 			struct stat stbuf;
    193 			char pathbuf[MAXPATHLEN];
    194 
    195 			if (strcmp(optarg, "co") == 0)
    196 				ttypath = _PATH_CONSOLE;
    197 			else if (*optarg != '/')
    198 				(void) sprintf(ttypath = pathbuf, "%s%s",
    199 				    _PATH_TTY, optarg);
    200 			else
    201 				ttypath = optarg;
    202 			if (stat(ttypath, &stbuf) == -1)
    203 				err("%s: %s", ttypath, strerror(errno));
    204 			if (!S_ISCHR(stbuf.st_mode))
    205 				err("%s: not a terminal", ttypath);
    206 			ttydev = stbuf.st_rdev;
    207 			break;
    208 		}
    209 		case 'u':
    210 			parsefmt(ufmt);
    211 			sortby = SORTCPU;
    212 			fmt = 1;
    213 			ufmt[0] = '\0';
    214 			break;
    215 		case 'v':
    216 			parsefmt(vfmt);
    217 			sortby = SORTMEM;
    218 			fmt = 1;
    219 			vfmt[0] = '\0';
    220 			break;
    221 		case 'W':
    222 			swapf = optarg;
    223 			break;
    224 		case 'w':
    225 			if (termwidth < 131)
    226 				termwidth = 131;
    227 			else
    228 				termwidth = UNLIMITED;
    229 			break;
    230 		case 'x':
    231 			xflg = 1;
    232 			break;
    233 		case '?':
    234 		default:
    235 			usage();
    236 		}
    237 	argc -= optind;
    238 	argv += optind;
    239 
    240 #define	BACKWARD_COMPATIBILITY
    241 #ifdef	BACKWARD_COMPATIBILITY
    242 	if (*argv) {
    243 
    244 		nlistf = *argv;
    245 		if (*++argv) {
    246 			memf = *argv;
    247 			if (*++argv)
    248 				swapf = *argv;
    249 		}
    250 	}
    251 #endif
    252 	if (kvm_openfiles(nlistf, memf, swapf) == -1)
    253 		err("kvm_openfiles: %s", kvm_geterr());
    254 
    255 	if (!fmt)
    256 		parsefmt(dfmt);
    257 
    258 	if (!all && ttydev == NODEV && pid == -1)  /* XXX - should be cleaner */
    259 		uid = getuid();
    260 
    261 	/*
    262 	 * scan requested variables, noting what structures are needed,
    263 	 * and adjusting header widths as appropiate.
    264 	 */
    265 	scanvars();
    266 	/*
    267 	 * get proc list
    268 	 */
    269 	if (uid != -1) {
    270 		what = KINFO_PROC_UID;
    271 		flag = uid;
    272 	} else if (ttydev != NODEV) {
    273 		what = KINFO_PROC_TTY;
    274 		flag = ttydev;
    275 	} else if (pid != -1) {
    276 		what = KINFO_PROC_PID;
    277 		flag = pid;
    278 	} else
    279 		what = KINFO_PROC_ALL;
    280 	/*
    281 	 * select procs
    282 	 */
    283 	if ((nentries = kvm_getprocs(what, flag)) == -1)
    284 		err("%s", kvm_geterr());
    285 	kinfo = malloc(nentries * sizeof(KINFO));
    286 	if (kinfo == NULL)
    287 		err("%s", strerror(errno));
    288 	for (nentries = 0; p = kvm_nextproc(); ++nentries) {
    289 		kinfo[nentries].ki_p = p;
    290 		kinfo[nentries].ki_e = kvm_geteproc(p);
    291 		if (needuser)
    292 			saveuser(&kinfo[nentries]);
    293 	}
    294 	/*
    295 	 * print header
    296 	 */
    297 	printheader();
    298 	if (nentries == 0)
    299 		exit(0);
    300 	/*
    301 	 * sort proc list
    302 	 */
    303 	qsort((void *)kinfo, nentries, sizeof(KINFO), pscomp);
    304 	/*
    305 	 * for each proc, call each variable output function.
    306 	 */
    307 	for (i = lineno = 0; i < nentries; i++) {
    308 		if (xflg == 0 && (kinfo[i].ki_e->e_tdev == NODEV ||
    309 		    (kinfo[i].ki_p->p_flag & SCTTY ) == 0))
    310 			continue;
    311 		for (vent = vhead; vent; vent = vent->next) {
    312 			(*vent->var->oproc)(&kinfo[i], vent->var, vent->next);
    313 			if (vent->next != NULL)
    314 				(void) putchar(' ');
    315 		}
    316 		(void) putchar('\n');
    317 		if (prtheader && lineno++ == prtheader-4) {
    318 			(void) putchar('\n');
    319 			printheader();
    320 			lineno = 0;
    321 		}
    322 	}
    323 	exit(eval);
    324 }
    325 
    326 scanvars()
    327 {
    328 	register struct varent *vent;
    329 	register VAR *v;
    330 	register int i;
    331 
    332 	for (vent = vhead; vent; vent = vent->next) {
    333 		v = vent->var;
    334 		i = strlen(v->header);
    335 		if (v->width < i)
    336 			v->width = i;
    337 		totwidth += v->width + 1;	/* +1 for space */
    338 		if (v->flag & USER)
    339 			needuser = 1;
    340 		if (v->flag & COMM)
    341 			needcomm = 1;
    342 	}
    343 	totwidth--;
    344 }
    345 
    346 
    347 /* XXX - redo */
    348 saveuser(ki)
    349 	KINFO *ki;
    350 {
    351 	register struct usave *usp;
    352 	register struct user *up;
    353 
    354 	if ((usp = calloc(1, sizeof(struct usave))) == NULL)
    355 		err("%s", strerror(errno));
    356 	up = kvm_getu(ki->ki_p);
    357 	/*
    358 	 * save arguments and environment if needed
    359 	 */
    360 	ki->ki_args = needcomm ? strdup(kvm_getargs(ki->ki_p, up)) : NULL;
    361 	ki->ki_env = needenv ? strdup(kvm_getenv(ki->ki_p, up)) : NULL;
    362 
    363 	if (up != NULL) {
    364 		ki->ki_u = usp;
    365 		/*
    366 		 * save important fields
    367 		 */
    368 #ifdef NEWVM
    369 		usp->u_start = up->u_stats.p_start;
    370 		usp->u_ru = up->u_stats.p_ru;
    371 		usp->u_cru = up->u_stats.p_cru;
    372 #else
    373 		usp->u_procp = up->u_procp;
    374 		usp->u_start = up->u_start;
    375 		usp->u_ru = up->u_ru;
    376 		usp->u_cru = up->u_cru;
    377 		usp->u_acflag = up->u_acflag;
    378 #endif
    379 	} else
    380 		free(usp);
    381 }
    382 
    383 pscomp(k1, k2)
    384 	KINFO *k1, *k2;
    385 {
    386 	int i;
    387 #ifdef NEWVM
    388 #define VSIZE(k) ((k)->ki_e->e_vm.vm_dsize + (k)->ki_e->e_vm.vm_ssize + \
    389 		  (k)->ki_e->e_vm.vm_tsize)
    390 #else
    391 #define VSIZE(k) ((k)->ki_p->p_dsize + (k)->ki_p->p_ssize + (k)->ki_e->e_xsize)
    392 #endif
    393 
    394 	if (sortby == SORTCPU)
    395 		return (getpcpu(k2) - getpcpu(k1));
    396 	if (sortby == SORTMEM)
    397 		return (VSIZE(k2) - VSIZE(k1));
    398 	i =  k1->ki_e->e_tdev - k2->ki_e->e_tdev;
    399 	if (i == 0)
    400 		i = k1->ki_p->p_pid - k2->ki_p->p_pid;
    401 	return (i);
    402 }
    403 
    404 /*
    405  * ICK (all for getopt), would rather hide the ugliness
    406  * here than taint the main code.
    407  *
    408  *  ps foo -> ps -foo
    409  *  ps 34 -> ps -p34
    410  *
    411  * The old convention that 't' with no trailing tty arg means the users
    412  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
    413  * feature is available with the option 'T', which takes no argument.
    414  */
    415 char *
    416 kludge_oldps_options(s)
    417 	char *s;
    418 {
    419 	size_t len;
    420 	char *newopts, *ns, *cp;
    421 
    422 	len = strlen(s);
    423 	if ((newopts = ns = malloc(len + 2)) == NULL)
    424 		err("%s", strerror(errno));
    425 	/*
    426 	 * options begin with '-'
    427 	 */
    428 	if (*s != '-')
    429 		*ns++ = '-';	/* add option flag */
    430 	/*
    431 	 * gaze to end of argv[1]
    432 	 */
    433 	cp = s + len - 1;
    434 	/*
    435 	 * if last letter is a 't' flag with no argument (in the context
    436 	 * of the oldps options -- option string NOT starting with a '-' --
    437 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
    438 	 */
    439 	if (*cp == 't' && *s != '-')
    440 		*cp = 'T';
    441 	else {
    442 		/*
    443 		 * otherwise check for trailing number, which *may* be a
    444 		 * pid.
    445 		 */
    446 		while (cp >= s && isdigit(*cp))
    447 			--cp;
    448 	}
    449 	cp++;
    450 	bcopy(s, ns, (size_t)(cp - s));	/* copy up to trailing number */
    451 	ns += cp - s;
    452 	/*
    453 	 * if there's a trailing number, and not a preceding 'p' (pid) or
    454 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
    455 	 */
    456 	if (isdigit(*cp) && (cp == s || cp[-1] != 't' && cp[-1] != 'p' &&
    457 	    (cp - 1 == s || cp[-2] != 't')))
    458 		*ns++ = 'p';
    459 	(void) strcpy(ns, cp);		/* and append the number */
    460 
    461 	return (newopts);
    462 }
    463 
    464 #if __STDC__
    465 #include <stdarg.h>
    466 #else
    467 #include <varargs.h>
    468 #endif
    469 
    470 void
    471 #if __STDC__
    472 err(const char *fmt, ...)
    473 #else
    474 err(fmt, va_alist)
    475 	char *fmt;
    476         va_dcl
    477 #endif
    478 {
    479 	va_list ap;
    480 #if __STDC__
    481 	va_start(ap, fmt);
    482 #else
    483 	va_start(ap);
    484 #endif
    485 	(void)fprintf(stderr, "ps: ");
    486 	(void)vfprintf(stderr, fmt, ap);
    487 	va_end(ap);
    488 	(void)fprintf(stderr, "\n");
    489 	exit(1);
    490 	/* NOTREACHED */
    491 }
    492 
    493 usage()
    494 {
    495 	(void) fprintf(stderr,
    496 "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]\n\t  [-M core] [-N system] [-W swap]\n       ps [-L]\n");
    497 	exit(1);
    498 }
    499