2 * Copyright (c) 1990, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
33 * @(#) Copyright (c) 1990, 1993, 1994 The Regents of the University of California. All rights reserved.
34 * @(#)ps.c 8.4 (Berkeley) 4/2/94
35 * $FreeBSD: src/bin/ps/ps.c,v 1.30.2.6 2002/07/04 08:30:37 sobomax Exp $
36 * $DragonFly: src/bin/ps/ps.c,v 1.22 2007/02/01 10:33:25 corecode Exp $
39 #include <sys/param.h>
42 #include <sys/queue.h>
43 #include <sys/resource.h>
45 #include <sys/ioctl.h>
46 #include <sys/sysctl.h>
66 #define SEP ", \t" /* username separators */
69 struct varent *vhead, *vtail;
71 int eval; /* exit value */
74 int sumrusage; /* -S */
75 int termwidth; /* width of screen (0 == infinity) */
76 int totwidth; /* calculated width of requested variables */
77 int numcpus; /* hw.ncpu */
79 static int needuser, needcomm, needenv;
81 static int forceuread=0;
82 #define PS_ARGS "aCcefghjLlM:mN:O:o:p:rSTt:U:uvwx"
84 static int forceuread=1;
85 #define PS_ARGS "aCceghjLlM:mN:O:o:p:rSTt:U:uvwx"
88 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
90 static const char *getfmt (char **(*)(kvm_t *, const struct kinfo_proc *, int),
91 KINFO *, char *, int);
92 static char *kludge_oldps_options (char *);
93 static int pscomp (const void *, const void *);
94 static void saveuser (KINFO *);
95 static void scanvars (void);
96 static void dynsizevars (KINFO *);
97 static void sizevars (void);
98 static void usage (void);
99 static uid_t *getuids(const char *, int *);
101 struct timeval btime;
103 static char dfmt[] = "pid tt state time command";
104 static char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
105 static char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
106 static char o1[] = "pid";
107 static char o2[] = "tt state time command";
108 static char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
109 static char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
114 main(int argc, char **argv)
116 struct kinfo_proc *kp;
122 int all, ch, flag, i, fmt, lineno, nentries, nocludge, dropgid;
123 int prtheader, wflag, what, xflg, uid, nuids;
124 char errbuf[_POSIX2_LINE_MAX];
125 const char *cp, *nlistf, *memf;
126 size_t btime_size = sizeof(struct timeval);
127 size_t numcpus_size = sizeof(numcpus);
129 setlocale(LC_ALL, "");
131 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
132 ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
133 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ws) == -1) ||
137 termwidth = ws.ws_col - 1;
140 * Don't apply a kludge if the first argument is an option taking an
145 if (argv[1][0] == '-') {
146 for (cp = PS_ARGS; *cp != '\0'; cp++) {
149 if (*(cp - 1) == argv[1][1]) {
156 argv[1] = kludge_oldps_options(argv[1]);
159 all = fmt = prtheader = wflag = xflg = 0;
165 memf = nlistf = _PATH_DEVNULL;
166 while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
177 case 'e': /* XXX set ufmt */
183 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
213 o1[0] = o2[0] = '\0';
222 if (getuid() == 0 || getgid() == 0)
237 if ((optarg = ttyname(STDIN_FILENO)) == NULL)
238 errx(1, "stdin: not a terminal");
242 char pathbuf[PATH_MAX];
245 if (strcmp(optarg, "co") == 0)
246 ttypath = _PATH_CONSOLE;
247 else if (*optarg != '/') {
249 sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
253 if (stat(ttypath, &sb) == -1)
254 err(1, "%s", ttypath);
255 if (!S_ISCHR(sb.st_mode))
256 errx(1, "%s: not a terminal", ttypath);
261 uids = getuids(optarg, &nuids);
262 xflg++; /* XXX: intuitive? */
278 termwidth = UNLIMITED;
279 else if (termwidth < 131)
293 #define BACKWARD_COMPATIBILITY
294 #ifdef BACKWARD_COMPATIBILITY
303 * Discard setgid privileges if not the running kernel so that bad
304 * guys can't print interesting stuff from kernel memory.
311 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
313 errx(1, "%s", errbuf);
318 /* XXX - should be cleaner */
319 if (!all && ttydev == NODEV && pid == -1 && !nuids) {
320 if ((uids = malloc(sizeof (*uids))) == NULL)
321 errx(1, "malloc: %s", strerror(errno));
327 * scan requested variables, noting what structures are needed,
328 * and adjusting header widths as appropriate.
335 if (sysctlbyname("kern.boottime", &btime, &btime_size, NULL, 0) < 0) {
336 perror("sysctl: kern.boottime");
343 if (sysctlbyname("hw.ncpu", &numcpus, &numcpus_size, NULL, 0) < 0)
350 what = KERN_PROC_UID;
352 } else if (ttydev != NODEV) {
353 what = KERN_PROC_TTY;
355 } else if (pid != -1) {
356 what = KERN_PROC_PID;
359 what = KERN_PROC_ALL;
365 if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == NULL)
366 errx(1, "%s", kvm_geterr(kd));
367 if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
369 for (i = nentries; --i >= 0; ++kp) {
370 kinfo[i].ki_proc = kp;
373 dynsizevars(&kinfo[i]);
387 qsort(kinfo, nentries, sizeof(KINFO), pscomp);
389 * for each proc, call each variable output function.
391 for (i = lineno = 0; i < nentries; i++) {
392 if (xflg == 0 && (KI_PROC(&kinfo[i], tdev) == NODEV ||
393 (KI_PROC(&kinfo[i], flags) & P_CONTROLT ) == 0))
396 for (uid = 0; uid < nuids; uid++)
397 if (KI_PROC(&kinfo[i], uid) ==
403 STAILQ_FOREACH(vent, &var_head, link) {
404 (vent->var->oproc)(&kinfo[i], vent);
405 if (STAILQ_NEXT(vent, link) != NULL)
409 if (prtheader && lineno++ == prtheader - 4) {
421 getuids(const char *arg, int *nuids)
423 char name[UT_NAMESIZE + 1];
425 uid_t *uids, *moreuids;
433 for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
434 if (l >= sizeof name) {
435 warnx("%.*s: name too long", (int)l, arg);
438 strncpy(name, arg, l);
440 if ((pwd = getpwnam(name)) == NULL) {
441 warnx("%s: no such user", name);
444 if (*nuids >= alloc) {
445 alloc = (alloc + 1) << 1;
446 moreuids = realloc(uids, alloc * sizeof (*uids));
447 if (moreuids == NULL) {
449 errx(1, "realloc: %s", strerror(errno));
453 uids[(*nuids)++] = pwd->pw_uid;
458 errx(1, "No users specified");
469 STAILQ_FOREACH(vent, &var_head, link) {
471 if (v->flag & DSIZ) {
472 vent->dwidth = vent->width;
483 dynsizevars(KINFO *ki)
489 STAILQ_FOREACH(vent, &var_head, link) {
491 if (!(v->flag & DSIZ))
496 if (vent->width > vent->dwidth)
497 vent->width = vent->dwidth;
508 STAILQ_FOREACH(vent, &var_head, link) {
510 i = strlen(vent->header);
513 totwidth += vent->width + 1; /* +1 for space */
519 getfmt(char **(*fn) (kvm_t *, const struct kinfo_proc *, int), KINFO *ki, char
525 fmt_argv((*fn)(kd, ki->ki_proc, termwidth), comm, maxlen)) == NULL)
534 * save arguments if needed
537 ki->ki_args = getfmt(kvm_getargv, ki, KI_PROC(ki, comm),
543 ki->ki_env = getfmt(kvm_getenvv, ki, (char *)NULL, 0);
550 pscomp(const void *a, const void *b)
553 #define VSIZE(k) (KI_PROC(k, vm_dsize) + KI_PROC(k, vm_ssize) + \
554 KI_PROC(k, vm_tsize))
557 if (sortby == SORTIAC)
558 return (KI_PROC((const KINFO *)a)->p_usdata.bsd4.interactive - KI_PROC((const KINFO *)b)->p_usdata.bsd4.interactive);
560 if (sortby == SORTCPU)
561 return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
562 if (sortby == SORTMEM)
563 return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
564 i = KI_PROC((const KINFO *)a, tdev) - KI_PROC((const KINFO *)b, tdev);
566 i = KI_PROC((const KINFO *)a, pid) - KI_PROC((const KINFO *)b, pid);
571 * ICK (all for getopt), would rather hide the ugliness
572 * here than taint the main code.
577 * The old convention that 't' with no trailing tty arg means the users
578 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
579 * feature is available with the option 'T', which takes no argument.
582 kludge_oldps_options(char *s)
585 char *newopts, *ns, *cp;
588 if ((newopts = ns = malloc(len + 2)) == NULL)
591 * options begin with '-'
594 *ns++ = '-'; /* add option flag */
596 * gaze to end of argv[1]
600 * if last letter is a 't' flag with no argument (in the context
601 * of the oldps options -- option string NOT starting with a '-' --
602 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
604 * However, if a flag accepting a string argument is found in the
605 * option string, the remainder of the string is the argument to
606 * that flag; do not modify that argument.
608 if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
612 * otherwise check for trailing number, which *may* be a
615 while (cp >= s && isdigit(*cp))
619 memmove(ns, s, (size_t)(cp - s)); /* copy up to trailing number */
622 * if there's a trailing number, and not a preceding 'p' (pid) or
623 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
626 (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
627 (cp - 1 == s || cp[-2] != 't'))
629 strcpy(ns, cp); /* and append the number */
638 fprintf(stderr, "%s\n%s\n%s\n",
639 "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
640 " [-M core] [-N system]",