Home | History | Annotate | Line # | Download | only in ps
ps.c revision 1.10
      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[] = "from: @(#)ps.c	5.43 (Berkeley) 7/1/91";*/
     42 static char rcsid[] = "$Id: ps.c,v 1.10 1994/05/05 02:04:31 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 P_PPWAIT
     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 #ifdef NEWVM
     92 	"pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
     93 #else
     94 	"pid state time sl re pagein vsz rss lim tsiz trs %cpu %mem command";
     95 #endif
     96 
     97 main(argc, argv)
     98 	int argc;
     99 	char **argv;
    100 {
    101 	extern char *optarg;
    102 	extern int optind;
    103 	register struct proc *p;
    104 	register size_t nentries;
    105 	register struct varent *vent;
    106 	register int i;
    107 	struct winsize ws;
    108 	dev_t ttydev;
    109 	int all, ch, flag, fmt, lineno, pid, prtheader, uid, wflag, what, xflg;
    110 	int pscomp();
    111 	char *nlistf, *memf, *swapf;
    112 	char *kludge_oldps_options();
    113 
    114 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    115 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    116 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
    117 	     ws.ws_col == 0)
    118 		termwidth = 79;
    119 	else
    120 		termwidth = ws.ws_col - 1;
    121 
    122 	if (argc > 1)
    123 		argv[1] = kludge_oldps_options(argv[1]);
    124 
    125 	fmt = 0;
    126 	all = wflag = xflg = 0;
    127 	pid = uid = -1;
    128 	ttydev = NODEV;
    129 	memf = nlistf = swapf = NULL;
    130 	while ((ch = getopt(argc, argv,
    131 	    "aCeghjLlM:mN:O:o:p:rSTt:uvW:wx")) != EOF)
    132 		switch((char)ch) {
    133 		case 'a':
    134 			all = 1;
    135 			break;
    136 		case 'C':
    137 			rawcpu = 1;
    138 			break;
    139 		case 'e':
    140 			needenv = 1;
    141 			break;
    142 		case 'g':
    143 			break;	/* no-op */
    144 		case 'h':
    145 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
    146 			break;
    147 		case 'j':
    148 			parsefmt(jfmt);
    149 			fmt = 1;
    150 			jfmt[0] = '\0';
    151 			break;
    152 		case 'L':
    153 			showkey();
    154 			exit(0);
    155 		case 'l':
    156 			parsefmt(lfmt);
    157 			fmt = 1;
    158 			lfmt[0] = '\0';
    159 			break;
    160 		case 'M':
    161 			memf = optarg;
    162 			break;
    163 		case 'm':
    164 			sortby = SORTMEM;
    165 			break;
    166 		case 'N':
    167 			nlistf = optarg;
    168 			break;
    169 		case 'O':
    170 			parsefmt(o1);
    171 			parsefmt(optarg);
    172 			parsefmt(o2);
    173 			o1[0] = o2[0] = '\0';
    174 			fmt = 1;
    175 			break;
    176 		case 'o':
    177 			parsefmt(optarg);
    178 			fmt = 1;
    179 			break;
    180 		case 'p':
    181 			pid = atoi(optarg);
    182 			xflg = 1;
    183 			break;
    184 		case 'r':
    185 			sortby = SORTCPU;
    186 			break;
    187 		case 'S':
    188 			sumrusage = 1;
    189 			break;
    190 		case 'T':
    191 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
    192 				err("stdin: not a terminal");
    193 			/* FALLTHROUGH */
    194 		case 't': {
    195 			char *ttypath;
    196 			struct stat stbuf;
    197 			char pathbuf[MAXPATHLEN];
    198 
    199 			if (strcmp(optarg, "co") == 0)
    200 				ttypath = _PATH_CONSOLE;
    201 			else if (*optarg != '/')
    202 				(void) sprintf(ttypath = pathbuf, "%s%s",
    203 				    _PATH_TTY, optarg);
    204 			else
    205 				ttypath = optarg;
    206 			if (stat(ttypath, &stbuf) == -1)
    207 				err("%s: %s", ttypath, strerror(errno));
    208 			if (!S_ISCHR(stbuf.st_mode))
    209 				err("%s: not a terminal", ttypath);
    210 			ttydev = stbuf.st_rdev;
    211 			break;
    212 		}
    213 		case 'u':
    214 			parsefmt(ufmt);
    215 			sortby = SORTCPU;
    216 			fmt = 1;
    217 			ufmt[0] = '\0';
    218 			break;
    219 		case 'v':
    220 			parsefmt(vfmt);
    221 			sortby = SORTMEM;
    222 			fmt = 1;
    223 			vfmt[0] = '\0';
    224 			break;
    225 		case 'W':
    226 			swapf = optarg;
    227 			break;
    228 		case 'w':
    229 			if (wflag)
    230 				termwidth = UNLIMITED;
    231 			else if (termwidth < 131)
    232 				termwidth = 131;
    233                         wflag++;
    234 			break;
    235 		case 'x':
    236 			xflg = 1;
    237 			break;
    238 		case '?':
    239 		default:
    240 			usage();
    241 		}
    242 	argc -= optind;
    243 	argv += optind;
    244 
    245 #define	BACKWARD_COMPATIBILITY
    246 #ifdef	BACKWARD_COMPATIBILITY
    247 	if (*argv) {
    248 
    249 		nlistf = *argv;
    250 		if (*++argv) {
    251 			memf = *argv;
    252 			if (*++argv)
    253 				swapf = *argv;
    254 		}
    255 	}
    256 #endif
    257 	if (kvm_openfiles(nlistf, memf, swapf) == -1)
    258 		err("kvm_openfiles: %s", kvm_geterr());
    259 
    260 	if (!fmt)
    261 		parsefmt(dfmt);
    262 
    263 	if (!all && ttydev == NODEV && pid == -1)  /* XXX - should be cleaner */
    264 		uid = getuid();
    265 
    266 	/*
    267 	 * scan requested variables, noting what structures are needed,
    268 	 * and adjusting header widths as appropiate.
    269 	 */
    270 	scanvars();
    271 	/*
    272 	 * get proc list
    273 	 */
    274 	if (uid != -1) {
    275 		what = KINFO_PROC_UID;
    276 		flag = uid;
    277 	} else if (ttydev != NODEV) {
    278 		what = KINFO_PROC_TTY;
    279 		flag = ttydev;
    280 	} else if (pid != -1) {
    281 		what = KINFO_PROC_PID;
    282 		flag = pid;
    283 	} else
    284 		what = KINFO_PROC_ALL;
    285 	/*
    286 	 * select procs
    287 	 */
    288 	if ((nentries = kvm_getprocs(what, flag)) == -1)
    289 		err("%s", kvm_geterr());
    290 	kinfo = malloc(nentries * sizeof(KINFO));
    291 	if (kinfo == NULL)
    292 		err("%s", strerror(errno));
    293 	for (nentries = 0; p = kvm_nextproc(); ++nentries) {
    294 		kinfo[nentries].ki_p = p;
    295 		kinfo[nentries].ki_e = kvm_geteproc(p);
    296 		if (needuser || needcomm)
    297 			saveuser(&kinfo[nentries]);
    298 	}
    299 	/*
    300 	 * print header
    301 	 */
    302 	printheader();
    303 	if (nentries == 0)
    304 		exit(0);
    305 	/*
    306 	 * sort proc list
    307 	 */
    308 	qsort((void *)kinfo, nentries, sizeof(KINFO), pscomp);
    309 	/*
    310 	 * for each proc, call each variable output function.
    311 	 */
    312 	for (i = lineno = 0; i < nentries; i++) {
    313 		if (xflg == 0 && (kinfo[i].ki_e->e_tdev == NODEV ||
    314 		    (kinfo[i].ki_p->p_flag & P_CONTROLT) == 0))
    315 			continue;
    316 		for (vent = vhead; vent; vent = vent->next) {
    317 			(*vent->var->oproc)(&kinfo[i], vent->var, vent->next);
    318 			if (vent->next != NULL)
    319 				(void) putchar(' ');
    320 		}
    321 		(void) putchar('\n');
    322 		if (prtheader && lineno++ == prtheader-4) {
    323 			(void) putchar('\n');
    324 			printheader();
    325 			lineno = 0;
    326 		}
    327 	}
    328 	exit(eval);
    329 }
    330 
    331 scanvars()
    332 {
    333 	register struct varent *vent;
    334 	register VAR *v;
    335 	register int i;
    336 
    337 	for (vent = vhead; vent; vent = vent->next) {
    338 		v = vent->var;
    339 		i = strlen(v->header);
    340 		if (v->width < i)
    341 			v->width = i;
    342 		totwidth += v->width + 1;	/* +1 for space */
    343 		if (v->flag & USER)
    344 			needuser = 1;
    345 		if (v->flag & COMM)
    346 			needcomm = 1;
    347 	}
    348 	totwidth--;
    349 }
    350 
    351 
    352 /* XXX - redo */
    353 saveuser(ki)
    354 	KINFO *ki;
    355 {
    356 	register struct usave *usp;
    357 	register struct user *up;
    358 
    359 	if ((usp = calloc(1, sizeof(struct usave))) == NULL)
    360 		err("%s", strerror(errno));
    361 	up = kvm_getu(ki->ki_p);
    362 	/*
    363 	 * save arguments and environment if needed
    364 	 */
    365 	ki->ki_args = needcomm ? strdup(kvm_getargs(ki->ki_p, up)) : NULL;
    366 	ki->ki_env = needenv ? strdup(kvm_getenv(ki->ki_p, up)) : NULL;
    367 
    368 	if (up != NULL) {
    369 		ki->ki_u = usp;
    370 		/*
    371 		 * save important fields
    372 		 */
    373 #ifdef NEWVM
    374 		usp->u_start = up->u_stats.p_start;
    375 		usp->u_ru = up->u_stats.p_ru;
    376 		usp->u_cru = up->u_stats.p_cru;
    377 #else
    378 		usp->u_procp = up->u_procp;
    379 		usp->u_start = up->u_start;
    380 		usp->u_ru = up->u_ru;
    381 		usp->u_cru = up->u_cru;
    382 		usp->u_acflag = up->u_acflag;
    383 #endif
    384 	} else
    385 		free(usp);
    386 }
    387 
    388 pscomp(k1, k2)
    389 	KINFO *k1, *k2;
    390 {
    391 	int i;
    392 #ifdef NEWVM
    393 #define VSIZE(k) ((k)->ki_e->e_vm.vm_dsize + (k)->ki_e->e_vm.vm_ssize + \
    394 		  (k)->ki_e->e_vm.vm_tsize)
    395 #else
    396 #define VSIZE(k) ((k)->ki_p->p_dsize + (k)->ki_p->p_ssize + (k)->ki_e->e_xsize)
    397 #endif
    398 
    399 	if (sortby == SORTCPU)
    400 		return (getpcpu(k2) - getpcpu(k1));
    401 	if (sortby == SORTMEM)
    402 		return (VSIZE(k2) - VSIZE(k1));
    403 	i =  k1->ki_e->e_tdev - k2->ki_e->e_tdev;
    404 	if (i == 0)
    405 		i = k1->ki_p->p_pid - k2->ki_p->p_pid;
    406 	return (i);
    407 }
    408 
    409 /*
    410  * ICK (all for getopt), would rather hide the ugliness
    411  * here than taint the main code.
    412  *
    413  *  ps foo -> ps -foo
    414  *  ps 34 -> ps -p34
    415  *
    416  * The old convention that 't' with no trailing tty arg means the users
    417  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
    418  * feature is available with the option 'T', which takes no argument.
    419  */
    420 char *
    421 kludge_oldps_options(s)
    422 	char *s;
    423 {
    424 	size_t len;
    425 	char *newopts, *ns, *cp;
    426 
    427 	len = strlen(s);
    428 	if ((newopts = ns = malloc(len + 2)) == NULL)
    429 		err("%s", strerror(errno));
    430 	/*
    431 	 * options begin with '-'
    432 	 */
    433 	if (*s != '-')
    434 		*ns++ = '-';	/* add option flag */
    435 	/*
    436 	 * gaze to end of argv[1]
    437 	 */
    438 	cp = s + len - 1;
    439 	/*
    440 	 * if last letter is a 't' flag with no argument (in the context
    441 	 * of the oldps options -- option string NOT starting with a '-' --
    442 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
    443 	 */
    444 	if (*cp == 't' && *s != '-')
    445 		*cp = 'T';
    446 	else {
    447 		/*
    448 		 * otherwise check for trailing number, which *may* be a
    449 		 * pid.
    450 		 */
    451 		while (cp >= s && isdigit(*cp))
    452 			--cp;
    453 	}
    454 	cp++;
    455 	bcopy(s, ns, (size_t)(cp - s));	/* copy up to trailing number */
    456 	ns += cp - s;
    457 	/*
    458 	 * if there's a trailing number, and not a preceding 'p' (pid) or
    459 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
    460 	 */
    461 	if (isdigit(*cp) && (cp == s || cp[-1] != 't' && cp[-1] != 'p' &&
    462 	    (cp - 1 == s || cp[-2] != 't')))
    463 		*ns++ = 'p';
    464 	(void) strcpy(ns, cp);		/* and append the number */
    465 
    466 	return (newopts);
    467 }
    468 
    469 #if __STDC__
    470 #include <stdarg.h>
    471 #else
    472 #include <varargs.h>
    473 #endif
    474 
    475 void
    476 #if __STDC__
    477 err(const char *fmt, ...)
    478 #else
    479 err(fmt, va_alist)
    480 	char *fmt;
    481         va_dcl
    482 #endif
    483 {
    484 	va_list ap;
    485 #if __STDC__
    486 	va_start(ap, fmt);
    487 #else
    488 	va_start(ap);
    489 #endif
    490 	(void)fprintf(stderr, "ps: ");
    491 	(void)vfprintf(stderr, fmt, ap);
    492 	va_end(ap);
    493 	(void)fprintf(stderr, "\n");
    494 	exit(1);
    495 	/* NOTREACHED */
    496 }
    497 
    498 usage()
    499 {
    500 	(void) fprintf(stderr,
    501 "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]\n\t  [-M core] [-N system] [-W swap]\n       ps [-L]\n");
    502 	exit(1);
    503 }
    504