ps.c revision 1.39 1 /* $NetBSD: ps.c,v 1.39 2000/06/07 04:58:01 simonb Exp $ */
2
3 /*-
4 * Copyright (c) 1990, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\n\
39 The Regents of the University of California. All rights reserved.\n");
40 #endif /* not lint */
41
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)ps.c 8.4 (Berkeley) 4/2/94";
45 #else
46 __RCSID("$NetBSD: ps.c,v 1.39 2000/06/07 04:58:01 simonb Exp $");
47 #endif
48 #endif /* not lint */
49
50 #include <sys/param.h>
51 #include <sys/user.h>
52 #include <sys/time.h>
53 #include <sys/resource.h>
54 #include <sys/proc.h>
55 #include <sys/stat.h>
56 #include <sys/ioctl.h>
57 #include <sys/sysctl.h>
58
59 #include <ctype.h>
60 #include <err.h>
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <kvm.h>
64 #include <limits.h>
65 #include <nlist.h>
66 #include <paths.h>
67 #include <pwd.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <unistd.h>
72
73 #include "ps.h"
74
75 struct kinfo_proc2 *kinfo;
76 struct varent *vhead, *vtail;
77
78 int eval; /* exit value */
79 int rawcpu; /* -C */
80 int sumrusage; /* -S */
81 int dontuseprocfs; /* -K */
82 int termwidth; /* width of screen (0 == infinity) */
83 int totwidth; /* calculated width of requested variables */
84
85 int needcomm, needenv, commandonly, use_procfs;
86 uid_t myuid;
87
88 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
89
90 static struct kinfo_proc2
91 *getkinfo_kvm __P((kvm_t *, int, int, int *));
92 static char *kludge_oldps_options __P((char *));
93 static int pscomp __P((const void *, const void *));
94 static void scanvars __P((void));
95 static void usage __P((void));
96 int main __P((int, char *[]));
97
98 char dfmt[] = "pid tt state time command";
99 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
100 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
101 char o1[] = "pid";
102 char o2[] = "tt state time command";
103 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
104 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
105
106 kvm_t *kd;
107
108 int
109 main(argc, argv)
110 int argc;
111 char *argv[];
112 {
113 struct varent *vent;
114 struct winsize ws;
115 int ch, flag, i, fmt, lineno, nentries;
116 int prtheader, wflag, what, xflg, mode;
117 char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
118 char *ttname;
119
120 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
121 ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
122 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ws) == -1) ||
123 ws.ws_col == 0)
124 termwidth = 79;
125 else
126 termwidth = ws.ws_col - 1;
127
128 if (argc > 1)
129 argv[1] = kludge_oldps_options(argv[1]);
130
131 fmt = prtheader = wflag = xflg = 0;
132 what = KERN_PROC_UID;
133 flag = myuid = getuid();
134 memf = nlistf = swapf = NULL;
135 mode = PRINTMODE;
136 while ((ch = getopt(argc, argv,
137 "acCeghjKLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
138 switch((char)ch) {
139 case 'a':
140 what = KERN_PROC_ALL;
141 flag = 0;
142 break;
143 case 'c':
144 commandonly = 1;
145 break;
146 case 'e': /* XXX set ufmt */
147 needenv = 1;
148 break;
149 case 'C':
150 rawcpu = 1;
151 break;
152 case 'g':
153 break; /* no-op */
154 case 'h':
155 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
156 break;
157 case 'j':
158 parsefmt(jfmt);
159 fmt = 1;
160 jfmt[0] = '\0';
161 break;
162 case 'K':
163 dontuseprocfs=1;
164 break;
165 case 'L':
166 showkey();
167 exit(0);
168 /* NOTREACHED */
169 case 'l':
170 parsefmt(lfmt);
171 fmt = 1;
172 lfmt[0] = '\0';
173 break;
174 case 'M':
175 memf = optarg;
176 dontuseprocfs = 1;
177 break;
178 case 'm':
179 sortby = SORTMEM;
180 break;
181 case 'N':
182 nlistf = optarg;
183 break;
184 case 'O':
185 parsefmt(o1);
186 parsefmt(optarg);
187 parsefmt(o2);
188 o1[0] = o2[0] = '\0';
189 fmt = 1;
190 break;
191 case 'o':
192 parsefmt(optarg);
193 fmt = 1;
194 break;
195 case 'p':
196 what = KERN_PROC_PID;
197 flag = atol(optarg);
198 xflg = 1;
199 break;
200 case 'r':
201 sortby = SORTCPU;
202 break;
203 case 'S':
204 sumrusage = 1;
205 break;
206 case 'T':
207 if ((ttname = ttyname(STDIN_FILENO)) == NULL)
208 errx(1, "stdin: not a terminal");
209 goto tty;
210 case 't':
211 ttname = optarg;
212 tty: {
213 struct stat sb;
214 char *ttypath, pathbuf[MAXPATHLEN];
215
216 flag = 0;
217 if (strcmp(ttname, "?") == 0)
218 flag = KERN_PROC_TTY_NODEV;
219 else if (strcmp(ttname, "-") == 0)
220 flag = KERN_PROC_TTY_REVOKE;
221 else if (strcmp(ttname, "co") == 0)
222 ttypath = _PATH_CONSOLE;
223 else if (*ttname != '/')
224 (void)snprintf(ttypath = pathbuf,
225 sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
226 else
227 ttypath = ttname;
228 what = KERN_PROC_TTY;
229 if (flag == 0) {
230 if (stat(ttypath, &sb) == -1)
231 err(1, "%s", ttypath);
232 if (!S_ISCHR(sb.st_mode))
233 errx(1, "%s: not a terminal", ttypath);
234 flag = sb.st_rdev;
235 }
236 break;
237 }
238 case 'U':
239 if (*optarg != '\0') {
240 struct passwd *pw;
241 char *ep;
242
243 what = KERN_PROC_UID;
244 pw = getpwnam(optarg);
245 if (pw == NULL) {
246 errno = 0;
247 flag = strtoul(optarg, &ep, 10);
248 if (errno)
249 err(1, "%s", optarg);
250 if (*ep != '\0')
251 errx(1, "%s: illegal user name",
252 optarg);
253 } else
254 flag = pw->pw_uid;
255 }
256 break;
257 case 'u':
258 parsefmt(ufmt);
259 sortby = SORTCPU;
260 fmt = 1;
261 ufmt[0] = '\0';
262 break;
263 case 'v':
264 parsefmt(vfmt);
265 sortby = SORTMEM;
266 fmt = 1;
267 vfmt[0] = '\0';
268 break;
269 case 'W':
270 swapf = optarg;
271 break;
272 case 'w':
273 if (wflag)
274 termwidth = UNLIMITED;
275 else if (termwidth < 131)
276 termwidth = 131;
277 wflag++;
278 break;
279 case 'x':
280 xflg = 1;
281 break;
282 case '?':
283 default:
284 usage();
285 }
286 argc -= optind;
287 argv += optind;
288
289 #define BACKWARD_COMPATIBILITY
290 #ifdef BACKWARD_COMPATIBILITY
291 if (*argv) {
292 nlistf = *argv;
293 if (*++argv) {
294 memf = *argv;
295 if (*++argv)
296 swapf = *argv;
297 }
298 }
299 #endif
300
301 if (nlistf == NULL && memf == NULL && swapf == NULL) {
302 kd = kvm_openfiles(nlistf, memf, swapf, KVM_NO_FILES, errbuf);
303 donlist_sysctl();
304 } else
305 kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
306
307 if (kd == 0) {
308 if (dontuseprocfs)
309 errx(1, "%s", errbuf);
310 else {
311 warnx("kvm_openfiles: %s", errbuf);
312 fprintf(stderr, "ps: falling back to /proc-based lookup\n");
313 }
314 }
315
316 if (!fmt)
317 parsefmt(dfmt);
318
319 /*
320 * scan requested variables, noting what structures are needed.
321 */
322 scanvars();
323
324 /*
325 * select procs
326 */
327 if (!kd || !(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
328 {
329 /* If/when the /proc-based code is ripped out
330 * again, make sure all references to the -K
331 * option are also pulled (getopt(), usage(),
332 * man page). See the man page comments about
333 * this for more details. */
334 if (kd)
335 warnx("%s.", kvm_geterr(kd));
336 if (dontuseprocfs)
337 exit(1);
338
339 /* procfs_getprocs supports all but the
340 * KERN_PROC_RUID flag. */
341 kinfo = getkinfo_procfs(what, flag, &nentries);
342 if (kinfo == 0)
343 errx(1, "fallback /proc-based lookup also failed. %s",
344 "Giving up...");
345 fprintf(stderr, "%s%s",
346 "Warning: /proc does not provide ",
347 "valid data for all fields.\n");
348 use_procfs = 1;
349 }
350 if (nentries == 0) {
351 printheader();
352 exit(0);
353 }
354 /*
355 * sort proc list
356 */
357 qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
358 /*
359 * For each proc, call each variable output function in
360 * "setwidth" mode to determine the widest element of
361 * the column.
362 */
363 if (mode == PRINTMODE)
364 for (i = 0; i < nentries; i++) {
365 struct kinfo_proc2 *ki = &kinfo[i];
366
367 if (xflg == 0 && (ki->p_tdev == NODEV ||
368 (ki->p_flag & P_CONTROLT) == 0))
369 continue;
370 for (vent = vhead; vent; vent = vent->next)
371 (vent->var->oproc)(ki, vent, WIDTHMODE);
372 }
373 /*
374 * Print header - AFTER determining process field widths.
375 * printheader() also adds up the total width of all
376 * fields the first time it's called.
377 */
378 printheader();
379 /*
380 * For each proc, call each variable output function in
381 * print mode.
382 */
383 for (i = lineno = 0; i < nentries; i++) {
384 struct kinfo_proc2 *ki = &kinfo[i];
385
386 if (xflg == 0 && (ki->p_tdev == NODEV ||
387 (ki->p_flag & P_CONTROLT ) == 0))
388 continue;
389 for (vent = vhead; vent; vent = vent->next) {
390 (vent->var->oproc)(ki, vent, mode);
391 if (vent->next != NULL)
392 (void)putchar(' ');
393 }
394 (void)putchar('\n');
395 if (prtheader && lineno++ == prtheader - 4) {
396 (void)putchar('\n');
397 printheader();
398 lineno = 0;
399 }
400 }
401 exit(eval);
402 /* NOTREACHED */
403 }
404
405 static struct kinfo_proc2 *
406 getkinfo_kvm(kd, what, flag, nentriesp)
407 kvm_t *kd;
408 int what, flag, *nentriesp;
409 {
410 return (kvm_getproc2(kd, what, flag, sizeof(struct kinfo_proc2),
411 nentriesp));
412 }
413
414 static void
415 scanvars()
416 {
417 struct varent *vent;
418 VAR *v;
419
420 for (vent = vhead; vent; vent = vent->next) {
421 v = vent->var;
422 if (v->flag & COMM)
423 needcomm = 1;
424 }
425 }
426
427 static int
428 pscomp(a, b)
429 const void *a, *b;
430 {
431 struct kinfo_proc2 *ka = (struct kinfo_proc2 *)a;
432 struct kinfo_proc2 *kb = (struct kinfo_proc2 *)b;
433
434 int i;
435 #define VSIZE(k) (k->p_vm_dsize + k->p_vm_ssize + k->p_vm_tsize)
436
437 if (sortby == SORTCPU)
438 return (getpcpu(kb) - getpcpu(ka));
439 if (sortby == SORTMEM)
440 return (VSIZE(kb) - VSIZE(ka));
441 i = ka->p_tdev - kb->p_tdev;
442 if (i == 0)
443 i = ka->p_pid - kb->p_pid;
444
445 if (i == 0)
446 i = ka->p_pid - kb->p_pid;
447 return (i);
448 }
449
450 /*
451 * ICK (all for getopt), would rather hide the ugliness
452 * here than taint the main code.
453 *
454 * ps foo -> ps -foo
455 * ps 34 -> ps -p34
456 *
457 * The old convention that 't' with no trailing tty arg means the user's
458 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
459 * feature is available with the option 'T', which takes no argument.
460 */
461 static char *
462 kludge_oldps_options(s)
463 char *s;
464 {
465 size_t len;
466 char *newopts, *ns, *cp;
467
468 len = strlen(s);
469 if ((newopts = ns = malloc(len + 3)) == NULL)
470 err(1, NULL);
471 /*
472 * options begin with '-'
473 */
474 if (*s != '-')
475 *ns++ = '-'; /* add option flag */
476 /*
477 * gaze to end of argv[1]
478 */
479 cp = s + len - 1;
480 /*
481 * if last letter is a 't' flag with no argument (in the context
482 * of the oldps options -- option string NOT starting with a '-' --
483 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
484 */
485 if (*cp == 't' && *s != '-')
486 *cp = 'T';
487 else {
488 /*
489 * otherwise check for trailing number, which *may* be a
490 * pid.
491 */
492 while (cp >= s && isdigit(*cp))
493 --cp;
494 }
495 cp++;
496 memmove(ns, s, (size_t)(cp - s)); /* copy up to trailing number */
497 ns += cp - s;
498 /*
499 * if there's a trailing number, and not a preceding 'p' (pid) or
500 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
501 */
502 if (isdigit(*cp) &&
503 (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
504 (cp - 1 == s || cp[-2] != 't'))))
505 *ns++ = 'p';
506 /* and append the number */
507 (void)strcpy(ns, cp); /* XXX strcpy is safe */
508
509 return (newopts);
510 }
511
512 static void
513 usage()
514 {
515
516 (void)fprintf(stderr,
517 "usage:\t%s\n\t %s\n\t%s\n",
518 "ps [-aChjKlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
519 "[-M core] [-N system] [-W swap] [-U username]",
520 "ps [-L]");
521 exit(1);
522 /* NOTREACHED */
523 }
524