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.25 2008/01/10 14:18:39 matthias 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>
47 #include <sys/mount.h>
67 #define SEP ", \t" /* username separators */
70 struct varent *vhead, *vtail;
72 int eval; /* exit value */
75 int sumrusage; /* -S */
76 int termwidth; /* width of screen (0 == infinity) */
77 int totwidth; /* calculated width of requested variables */
78 int numcpus; /* hw.ncpu */
80 static int needuser, needcomm, needenv;
82 static int forceuread=0;
83 #define PS_ARGS "aCcefgHhjLlM:mN:O:o:p:rSTt:U:uvwx"
85 static int forceuread=1;
86 #define PS_ARGS "aCcegHhjLlM:mN:O:o:p:rSTt:U:uvwx"
89 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
91 static const char *getfmt (char **(*)(kvm_t *, const struct kinfo_proc *, int),
92 KINFO *, char *, int);
93 static char *kludge_oldps_options (char *);
94 static int pscomp (const void *, const void *);
95 static void saveuser (KINFO *);
96 static void scanvars (void);
97 static void dynsizevars (KINFO *);
98 static void sizevars (void);
99 static int check_procfs(void);
100 static void usage (void);
101 static uid_t *getuids(const char *, int *);
103 struct timeval btime;
105 static char dfmt[] = "pid tt state time command";
106 static char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
107 static char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
108 static char o1[] = "pid";
109 static char o2[] = "tt state time command";
110 static char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
111 static char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
116 main(int argc, char **argv)
118 struct kinfo_proc *kp;
124 int all, ch, flag, i, fmt, ofmt, lineno, nentries, nocludge, dropgid;
125 int prtheader, wflag, what, xflg, uid, nuids, showtid;
126 char errbuf[_POSIX2_LINE_MAX];
127 const char *cp, *nlistf, *memf;
128 size_t btime_size = sizeof(struct timeval);
129 size_t numcpus_size = sizeof(numcpus);
131 setlocale(LC_ALL, "");
133 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
134 ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
135 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ws) == -1) ||
139 termwidth = ws.ws_col - 1;
142 * Don't apply a kludge if the first argument is an option taking an
147 if (argv[1][0] == '-') {
148 for (cp = PS_ARGS; *cp != '\0'; cp++) {
151 if (*(cp - 1) == argv[1][1]) {
158 argv[1] = kludge_oldps_options(argv[1]);
161 all = fmt = ofmt = prtheader = wflag = xflg = showtid = 0;
167 memf = nlistf = _PATH_DEVNULL;
168 while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
179 case 'e': /* XXX set ufmt */
185 showtid = KERN_PROC_FLAG_LWP;
188 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
218 o1[0] = o2[0] = '\0';
227 if (getuid() == 0 || getgid() == 0)
242 if ((optarg = ttyname(STDIN_FILENO)) == NULL)
243 errx(1, "stdin: not a terminal");
247 char pathbuf[PATH_MAX];
250 if (strcmp(optarg, "co") == 0)
251 ttypath = _PATH_CONSOLE;
252 else if (*optarg != '/') {
254 sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
258 if (stat(ttypath, &sb) == -1)
259 err(1, "%s", ttypath);
260 if (!S_ISCHR(sb.st_mode))
261 errx(1, "%s: not a terminal", ttypath);
266 uids = getuids(optarg, &nuids);
267 xflg++; /* XXX: intuitive? */
283 termwidth = UNLIMITED;
284 else if (termwidth < 131)
299 * If the user specified ps -e then they want a copy of the process
300 * environment kvm_getenvv(3) attempts to open /proc/<pid>/mem.
301 * Check to make sure that procfs is mounted on /proc, otherwise
302 * print a warning informing the user that output will be incomplete.
304 if (needenv == 1 && check_procfs() == 0)
305 warnx("Process environment requires procfs(5)");
307 #define BACKWARD_COMPATIBILITY
308 #ifdef BACKWARD_COMPATIBILITY
317 * Discard setgid privileges if not the running kernel so that bad
318 * guys can't print interesting stuff from kernel memory.
325 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
327 errx(1, "%s", errbuf);
333 * Add TID to output format if requested unless user-specific format
336 if (showtid && !ofmt)
339 /* XXX - should be cleaner */
340 if (!all && ttydev == NODEV && pid == -1 && !nuids) {
341 if ((uids = malloc(sizeof (*uids))) == NULL)
342 errx(1, "malloc: %s", strerror(errno));
348 * scan requested variables, noting what structures are needed,
349 * and adjusting header widths as appropriate.
356 if (sysctlbyname("kern.boottime", &btime, &btime_size, NULL, 0) < 0) {
357 perror("sysctl: kern.boottime");
364 if (sysctlbyname("hw.ncpu", &numcpus, &numcpus_size, NULL, 0) < 0)
371 what = KERN_PROC_UID;
373 } else if (ttydev != NODEV) {
374 what = KERN_PROC_TTY;
376 } else if (pid != -1) {
377 what = KERN_PROC_PID;
380 what = KERN_PROC_ALL;
388 if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == NULL)
389 errx(1, "%s", kvm_geterr(kd));
390 if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
392 for (i = nentries; --i >= 0; ++kp) {
393 kinfo[i].ki_proc = kp;
396 dynsizevars(&kinfo[i]);
410 qsort(kinfo, nentries, sizeof(KINFO), pscomp);
412 * for each proc, call each variable output function.
414 for (i = lineno = 0; i < nentries; i++) {
415 if (xflg == 0 && (KI_PROC(&kinfo[i], tdev) == NODEV ||
416 (KI_PROC(&kinfo[i], flags) & P_CONTROLT ) == 0))
419 for (uid = 0; uid < nuids; uid++)
420 if (KI_PROC(&kinfo[i], uid) ==
426 STAILQ_FOREACH(vent, &var_head, link) {
427 (vent->var->oproc)(&kinfo[i], vent);
428 if (STAILQ_NEXT(vent, link) != NULL)
432 if (prtheader && lineno++ == prtheader - 4) {
444 getuids(const char *arg, int *nuids)
446 char name[UT_NAMESIZE + 1];
448 uid_t *uids, *moreuids;
456 for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
457 if (l >= sizeof name) {
458 warnx("%.*s: name too long", (int)l, arg);
461 strncpy(name, arg, l);
463 if ((pwd = getpwnam(name)) == NULL) {
464 warnx("%s: no such user", name);
467 if (*nuids >= alloc) {
468 alloc = (alloc + 1) << 1;
469 moreuids = realloc(uids, alloc * sizeof (*uids));
470 if (moreuids == NULL) {
472 errx(1, "realloc: %s", strerror(errno));
476 uids[(*nuids)++] = pwd->pw_uid;
481 errx(1, "No users specified");
492 STAILQ_FOREACH(vent, &var_head, link) {
494 if (v->flag & DSIZ) {
495 vent->dwidth = vent->width;
506 dynsizevars(KINFO *ki)
512 STAILQ_FOREACH(vent, &var_head, link) {
514 if (!(v->flag & DSIZ))
519 if (vent->width > vent->dwidth)
520 vent->width = vent->dwidth;
531 STAILQ_FOREACH(vent, &var_head, link) {
533 i = strlen(vent->header);
536 totwidth += vent->width + 1; /* +1 for space */
542 getfmt(char **(*fn) (kvm_t *, const struct kinfo_proc *, int), KINFO *ki, char
548 fmt_argv((*fn)(kd, ki->ki_proc, termwidth), comm, maxlen)) == NULL)
557 * save arguments if needed
560 ki->ki_args = getfmt(kvm_getargv, ki, KI_PROC(ki, comm),
566 ki->ki_env = getfmt(kvm_getenvv, ki, (char *)NULL, 0);
573 pscomp(const void *a, const void *b)
576 #define VSIZE(k) (KI_PROC(k, vm_dsize) + KI_PROC(k, vm_ssize) + \
577 KI_PROC(k, vm_tsize))
580 if (sortby == SORTIAC)
581 return (KI_PROC((const KINFO *)a)->p_usdata.bsd4.interactive - KI_PROC((const KINFO *)b)->p_usdata.bsd4.interactive);
583 if (sortby == SORTCPU)
584 return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
585 if (sortby == SORTMEM)
586 return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
587 i = KI_PROC((const KINFO *)a, tdev) - KI_PROC((const KINFO *)b, tdev);
589 i = KI_PROC((const KINFO *)a, pid) - KI_PROC((const KINFO *)b, pid);
594 * ICK (all for getopt), would rather hide the ugliness
595 * here than taint the main code.
600 * The old convention that 't' with no trailing tty arg means the users
601 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
602 * feature is available with the option 'T', which takes no argument.
605 kludge_oldps_options(char *s)
608 char *newopts, *ns, *cp;
611 if ((newopts = ns = malloc(len + 2)) == NULL)
614 * options begin with '-'
617 *ns++ = '-'; /* add option flag */
619 * gaze to end of argv[1]
623 * if last letter is a 't' flag with no argument (in the context
624 * of the oldps options -- option string NOT starting with a '-' --
625 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
627 * However, if a flag accepting a string argument is found in the
628 * option string, the remainder of the string is the argument to
629 * that flag; do not modify that argument.
631 if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
635 * otherwise check for trailing number, which *may* be a
638 while (cp >= s && isdigit(*cp))
642 memmove(ns, s, (size_t)(cp - s)); /* copy up to trailing number */
645 * if there's a trailing number, and not a preceding 'p' (pid) or
646 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
649 (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
650 (cp - 1 == s || cp[-2] != 't'))
652 strcpy(ns, cp); /* and append the number */
662 if (statfs("/proc", &mnt) < 0)
664 if (strcmp(mnt.f_fstypename, "procfs") != 0)
673 fprintf(stderr, "%s\n%s\n%s\n",
674 "usage: ps [-aChHjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
675 " [-M core] [-N system]",