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