ps.c revision 1.38 1 /* $NetBSD: ps.c,v 1.38 2000/05/26 03:04:28 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.38 2000/05/26 03:04:28 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=0; /* -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;
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 while ((ch = getopt(argc, argv,
136 "acCeghjKLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
137 switch((char)ch) {
138 case 'a':
139 what = KERN_PROC_ALL;
140 flag = 0;
141 break;
142 case 'c':
143 commandonly = 1;
144 break;
145 case 'e': /* XXX set ufmt */
146 needenv = 1;
147 break;
148 case 'C':
149 rawcpu = 1;
150 break;
151 case 'g':
152 break; /* no-op */
153 case 'h':
154 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
155 break;
156 case 'j':
157 parsefmt(jfmt);
158 fmt = 1;
159 jfmt[0] = '\0';
160 break;
161 case 'K':
162 dontuseprocfs=1;
163 break;
164 case 'L':
165 showkey();
166 exit(0);
167 /* NOTREACHED */
168 case 'l':
169 parsefmt(lfmt);
170 fmt = 1;
171 lfmt[0] = '\0';
172 break;
173 case 'M':
174 memf = optarg;
175 dontuseprocfs = 1;
176 break;
177 case 'm':
178 sortby = SORTMEM;
179 break;
180 case 'N':
181 nlistf = optarg;
182 break;
183 case 'O':
184 parsefmt(o1);
185 parsefmt(optarg);
186 parsefmt(o2);
187 o1[0] = o2[0] = '\0';
188 fmt = 1;
189 break;
190 case 'o':
191 parsefmt(optarg);
192 fmt = 1;
193 break;
194 case 'p':
195 what = KERN_PROC_PID;
196 flag = atol(optarg);
197 xflg = 1;
198 break;
199 case 'r':
200 sortby = SORTCPU;
201 break;
202 case 'S':
203 sumrusage = 1;
204 break;
205 case 'T':
206 if ((ttname = ttyname(STDIN_FILENO)) == NULL)
207 errx(1, "stdin: not a terminal");
208 goto tty;
209 case 't':
210 ttname = optarg;
211 tty: {
212 struct stat sb;
213 char *ttypath, pathbuf[MAXPATHLEN];
214
215 flag = 0;
216 if (strcmp(ttname, "?") == 0)
217 flag = KERN_PROC_TTY_NODEV;
218 else if (strcmp(ttname, "-") == 0)
219 flag = KERN_PROC_TTY_REVOKE;
220 else if (strcmp(ttname, "co") == 0)
221 ttypath = _PATH_CONSOLE;
222 else if (*ttname != '/')
223 (void)snprintf(ttypath = pathbuf,
224 sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
225 else
226 ttypath = ttname;
227 what = KERN_PROC_TTY;
228 if (flag == 0) {
229 if (stat(ttypath, &sb) == -1)
230 err(1, "%s", ttypath);
231 if (!S_ISCHR(sb.st_mode))
232 errx(1, "%s: not a terminal", ttypath);
233 flag = sb.st_rdev;
234 }
235 break;
236 }
237 case 'U':
238 if (*optarg != '\0') {
239 struct passwd *pw;
240 char *ep;
241
242 what = KERN_PROC_UID;
243 pw = getpwnam(optarg);
244 if (pw == NULL) {
245 errno = 0;
246 flag = strtoul(optarg, &ep, 10);
247 if (errno)
248 err(1, "%s", optarg);
249 if (*ep != '\0')
250 errx(1, "%s: illegal user name",
251 optarg);
252 } else
253 flag = pw->pw_uid;
254 }
255 break;
256 case 'u':
257 parsefmt(ufmt);
258 sortby = SORTCPU;
259 fmt = 1;
260 ufmt[0] = '\0';
261 break;
262 case 'v':
263 parsefmt(vfmt);
264 sortby = SORTMEM;
265 fmt = 1;
266 vfmt[0] = '\0';
267 break;
268 case 'W':
269 swapf = optarg;
270 break;
271 case 'w':
272 if (wflag)
273 termwidth = UNLIMITED;
274 else if (termwidth < 131)
275 termwidth = 131;
276 wflag++;
277 break;
278 case 'x':
279 xflg = 1;
280 break;
281 case '?':
282 default:
283 usage();
284 }
285 argc -= optind;
286 argv += optind;
287
288 #define BACKWARD_COMPATIBILITY
289 #ifdef BACKWARD_COMPATIBILITY
290 if (*argv) {
291 nlistf = *argv;
292 if (*++argv) {
293 memf = *argv;
294 if (*++argv)
295 swapf = *argv;
296 }
297 }
298 #endif
299
300 if (nlistf == NULL && memf == NULL && swapf == NULL) {
301 kd = kvm_openfiles(nlistf, memf, swapf, KVM_NO_FILES, errbuf);
302 donlist_sysctl();
303 } else
304 kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
305
306 if (kd == 0) {
307 if (dontuseprocfs)
308 errx(1, "%s", errbuf);
309 else {
310 warnx("kvm_openfiles: %s", errbuf);
311 fprintf(stderr, "ps: falling back to /proc-based lookup\n");
312 }
313 }
314
315 if (!fmt)
316 parsefmt(dfmt);
317
318 /*
319 * scan requested variables, noting what structures are needed,
320 * and adjusting header widths as appropiate.
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
351 /*
352 * print header
353 */
354 printheader();
355 if (nentries == 0)
356 exit(0);
357 /*
358 * sort proc list
359 */
360 qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
361 /*
362 * for each proc, call each variable output function.
363 */
364 for (i = lineno = 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);
372 if (vent->next != NULL)
373 (void)putchar(' ');
374 }
375 (void)putchar('\n');
376 if (prtheader && lineno++ == prtheader - 4) {
377 (void)putchar('\n');
378 printheader();
379 lineno = 0;
380 }
381 }
382 exit(eval);
383 /* NOTREACHED */
384 }
385
386 static struct kinfo_proc2 *
387 getkinfo_kvm(kd, what, flag, nentriesp)
388 kvm_t *kd;
389 int what, flag, *nentriesp;
390 {
391 return (kvm_getproc2(kd, what, flag, sizeof(struct kinfo_proc2),
392 nentriesp));
393 }
394
395 static void
396 scanvars()
397 {
398 struct varent *vent;
399 VAR *v;
400 int i;
401
402 for (vent = vhead; vent; vent = vent->next) {
403 v = vent->var;
404 i = strlen(v->header);
405 if (v->width < i)
406 v->width = i;
407 totwidth += v->width + 1; /* +1 for space */
408 if (v->flag & COMM)
409 needcomm = 1;
410 }
411 totwidth--;
412 }
413
414 static int
415 pscomp(a, b)
416 const void *a, *b;
417 {
418 struct kinfo_proc2 *ka = (struct kinfo_proc2 *)a;
419 struct kinfo_proc2 *kb = (struct kinfo_proc2 *)b;
420
421 int i;
422 #define VSIZE(k) (k->p_vm_dsize + k->p_vm_ssize + k->p_vm_tsize)
423
424 if (sortby == SORTCPU)
425 return (getpcpu(kb) - getpcpu(ka));
426 if (sortby == SORTMEM)
427 return (VSIZE(kb) - VSIZE(ka));
428 i = ka->p_tdev - kb->p_tdev;
429 if (i == 0)
430 i = ka->p_pid - kb->p_pid;
431
432 if (i == 0)
433 i = ka->p_pid - kb->p_pid;
434 return (i);
435 }
436
437 /*
438 * ICK (all for getopt), would rather hide the ugliness
439 * here than taint the main code.
440 *
441 * ps foo -> ps -foo
442 * ps 34 -> ps -p34
443 *
444 * The old convention that 't' with no trailing tty arg means the user's
445 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
446 * feature is available with the option 'T', which takes no argument.
447 */
448 static char *
449 kludge_oldps_options(s)
450 char *s;
451 {
452 size_t len;
453 char *newopts, *ns, *cp;
454
455 len = strlen(s);
456 if ((newopts = ns = malloc(len + 3)) == NULL)
457 err(1, NULL);
458 /*
459 * options begin with '-'
460 */
461 if (*s != '-')
462 *ns++ = '-'; /* add option flag */
463 /*
464 * gaze to end of argv[1]
465 */
466 cp = s + len - 1;
467 /*
468 * if last letter is a 't' flag with no argument (in the context
469 * of the oldps options -- option string NOT starting with a '-' --
470 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
471 */
472 if (*cp == 't' && *s != '-')
473 *cp = 'T';
474 else {
475 /*
476 * otherwise check for trailing number, which *may* be a
477 * pid.
478 */
479 while (cp >= s && isdigit(*cp))
480 --cp;
481 }
482 cp++;
483 memmove(ns, s, (size_t)(cp - s)); /* copy up to trailing number */
484 ns += cp - s;
485 /*
486 * if there's a trailing number, and not a preceding 'p' (pid) or
487 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
488 */
489 if (isdigit(*cp) &&
490 (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
491 (cp - 1 == s || cp[-2] != 't'))))
492 *ns++ = 'p';
493 /* and append the number */
494 (void)strcpy(ns, cp); /* XXX strcpy is safe */
495
496 return (newopts);
497 }
498
499 static void
500 usage()
501 {
502
503 (void)fprintf(stderr,
504 "usage:\t%s\n\t %s\n\t%s\n",
505 "ps [-aChjKlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
506 "[-M core] [-N system] [-W swap] [-U username]",
507 "ps [-L]");
508 exit(1);
509 /* NOTREACHED */
510 }
511