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. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#) Copyright (c) 1990, 1993, 1994 The Regents of the University of California. All rights reserved.
30 * @(#)ps.c 8.4 (Berkeley) 4/2/94
31 * $FreeBSD: src/bin/ps/ps.c,v 1.30.2.6 2002/07/04 08:30:37 sobomax Exp $
35 #include <sys/param.h>
37 #include <sys/queue.h>
38 #include <sys/resource.h>
40 #include <sys/ioctl.h>
41 #include <sys/sysctl.h>
42 #include <sys/mount.h>
61 #define SEP ", \t" /* username separators */
64 #define KHMASK (KHSIZE - 1)
68 struct varent
*vhead
, *vtail
;
70 int eval
; /* exit value */
73 int sumrusage
; /* -S */
74 int termwidth
; /* width of screen (0 == infinity) */
75 int totwidth
; /* calculated width of requested variables */
76 int numcpus
; /* hw.ncpu */
79 static int needuser
, needcomm
, needenv
;
81 static int forceuread
=0;
82 #define PS_ARGS "AaCcefgHhjLlM:mN:O:o:p:rRSTt:U:uvwx"
84 static int forceuread
=1;
85 #define PS_ARGS "AaCcegHhjLlM:mN:O:o:p:rRSTt: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 dochain (KINFO
**ksort
, int *nentriesp
, pid_t pid
);
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
;
127 char errbuf
[_POSIX2_LINE_MAX
];
128 const char *cp
, *nlistf
, *memf
;
129 size_t btime_size
= sizeof(struct timeval
);
130 size_t numcpus_size
= sizeof(numcpus
);
132 setlocale(LC_ALL
, "");
134 if ((ioctl(STDOUT_FILENO
, TIOCGWINSZ
, (char *)&ws
) == -1 &&
135 ioctl(STDERR_FILENO
, TIOCGWINSZ
, (char *)&ws
) == -1 &&
136 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ws
) == -1) ||
140 termwidth
= ws
.ws_col
- 1;
143 * Don't apply a kludge if the first argument is an option taking an
148 if (argv
[1][0] == '-') {
149 for (cp
= PS_ARGS
; *cp
!= '\0'; cp
++) {
152 if (*(cp
- 1) == argv
[1][1]) {
159 argv
[1] = kludge_oldps_options(argv
[1]);
162 all
= fmt
= ofmt
= prtheader
= wflag
= xflg
= showtid
= 0;
169 memf
= nlistf
= _PATH_DEVNULL
;
171 while ((ch
= getopt(argc
, argv
, PS_ARGS
)) != -1) {
185 case 'e': /* XXX set ufmt */
191 showtid
= KERN_PROC_FLAG_LWP
;
194 prtheader
= ws
.ws_row
> 5 ? ws
.ws_row
: 22;
224 o1
[0] = o2
[0] = '\0';
233 if (getuid() == 0 || getgid() == 0)
251 if ((optarg
= ttyname(STDIN_FILENO
)) == NULL
)
252 errx(1, "stdin: not a terminal");
256 char pathbuf
[PATH_MAX
];
259 if (strcmp(optarg
, "co") == 0) {
260 ttypath
= _PATH_CONSOLE
;
261 } else if (*optarg
>= '0' && *optarg
<= '9') {
262 snprintf(pathbuf
, sizeof(pathbuf
),
263 "%spts/%s", _PATH_DEV
, optarg
);
265 } else if (*optarg
!= '/') {
266 snprintf(pathbuf
, sizeof(pathbuf
),
267 "%s%s", _PATH_TTY
, optarg
);
272 if (stat(ttypath
, &sb
) == -1)
273 err(1, "%s", ttypath
);
274 if (!S_ISCHR(sb
.st_mode
))
275 errx(1, "%s: not a terminal", ttypath
);
280 uids
= getuids(optarg
, &nuids
);
281 xflg
++; /* XXX: intuitive? */
297 termwidth
= UNLIMITED
;
298 else if (termwidth
< 131)
314 * If the user specified ps -e then they want a copy of the process
315 * environment kvm_getenvv(3) attempts to open /proc/<pid>/mem.
316 * Check to make sure that procfs is mounted on /proc, otherwise
317 * print a warning informing the user that output will be incomplete.
319 if (needenv
== 1 && check_procfs() == 0)
320 warnx("Process environment requires procfs(5)");
322 #define BACKWARD_COMPATIBILITY
323 #ifdef BACKWARD_COMPATIBILITY
332 * Discard setgid privileges if not the running kernel so that bad
333 * guys can't print interesting stuff from kernel memory.
340 kd
= kvm_openfiles(nlistf
, memf
, NULL
, O_RDONLY
, errbuf
);
342 errx(1, "%s", errbuf
);
348 * Add TID to output format if requested unless user-specific format
351 if (showtid
&& !ofmt
)
354 /* XXX - should be cleaner */
355 if (!all
&& ttydev
== NODEV
&& pid
== -1 && !nuids
) {
356 if ((uids
= malloc(sizeof (*uids
))) == NULL
)
357 errx(1, "malloc: %s", strerror(errno
));
363 * scan requested variables, noting what structures are needed,
364 * and adjusting header widths as appropriate.
371 if (sysctlbyname("kern.boottime", &btime
, &btime_size
, NULL
, 0) < 0) {
372 perror("sysctl: kern.boottime");
379 if (sysctlbyname("hw.ncpu", &numcpus
, &numcpus_size
, NULL
, 0) < 0)
386 what
= KERN_PROC_UID
;
388 } else if (ttydev
!= NODEV
) {
389 what
= KERN_PROC_TTY
;
391 } else if (pid
!= -1 && chainflg
== 0) {
392 what
= KERN_PROC_PID
;
395 what
= KERN_PROC_ALL
;
403 if ((kp
= kvm_getprocs(kd
, what
, flag
, &nentries
)) == NULL
)
404 errx(1, "%s", kvm_geterr(kd
));
405 if ((KInfo
= calloc(nentries
, sizeof(KINFO
))) == NULL
)
407 if ((KSort
= malloc(nentries
* sizeof(KINFO
*))) == NULL
)
410 for (i
= 0; i
< nentries
; ++i
) {
411 KInfo
[i
].ki_proc
= &kp
[i
];
412 KInfo
[i
].ki_indent
= -1;
413 KInfo
[i
].ki_ctailp
= &KInfo
[i
].ki_cbase
;
416 dynsizevars(&KInfo
[i
]);
417 KSort
[i
] = &KInfo
[i
];
431 qsort(KSort
, nentries
, sizeof(KINFO
*), pscomp
);
434 * rejigger and indent children, parent(s) and children
435 * at each level retain the above sort characteristics.
438 dochain(KSort
, &nentries
, pid
);
441 * for each proc, call each variable output function.
443 for (i
= lineno
= 0; i
< nentries
; i
++) {
444 if (xflg
== 0 && (KI_PROC(KSort
[i
], tdev
) == NODEV
||
445 (KI_PROC(KSort
[i
], flags
) & P_CONTROLT
) == 0))
448 for (uid
= 0; uid
< nuids
; uid
++)
449 if (KI_PROC(KSort
[i
], uid
) ==
455 STAILQ_FOREACH(vent
, &var_head
, link
) {
456 (vent
->var
->oproc
)(KSort
[i
], vent
);
457 if (STAILQ_NEXT(vent
, link
) != NULL
)
461 if (prtheader
&& lineno
++ == prtheader
- 4) {
473 getuids(const char *arg
, int *nuids
)
475 char name
[MAXLOGNAME
];
477 uid_t
*uids
, *moreuids
;
485 for (; (l
= strcspn(arg
, SEP
)) > 0; arg
+= l
+ strspn(arg
+ l
, SEP
)) {
486 if (l
>= sizeof name
) {
487 warnx("%.*s: name too long", (int)l
, arg
);
490 strncpy(name
, arg
, l
);
492 if ((pwd
= getpwnam(name
)) == NULL
) {
493 warnx("%s: no such user", name
);
496 if (*nuids
>= alloc
) {
497 alloc
= (alloc
+ 1) << 1;
498 moreuids
= realloc(uids
, alloc
* sizeof (*uids
));
499 if (moreuids
== NULL
) {
501 errx(1, "realloc: %s", strerror(errno
));
505 uids
[(*nuids
)++] = pwd
->pw_uid
;
510 errx(1, "No users specified");
521 STAILQ_FOREACH(vent
, &var_head
, link
) {
523 if (v
->flag
& DSIZ
) {
524 vent
->dwidth
= vent
->width
;
535 dynsizevars(KINFO
*ki
)
541 STAILQ_FOREACH(vent
, &var_head
, link
) {
543 if (!(v
->flag
& DSIZ
))
548 if (vent
->width
> vent
->dwidth
)
549 vent
->width
= vent
->dwidth
;
559 STAILQ_FOREACH(vent
, &var_head
, link
) {
560 i
= strlen(vent
->header
);
563 totwidth
+= vent
->width
+ 1; /* +1 for space */
569 getfmt(char **(*fn
) (kvm_t
*, const struct kinfo_proc
*, int), KINFO
*ki
, char
575 fmt_argv((*fn
)(kd
, ki
->ki_proc
, termwidth
), comm
, maxlen
)) == NULL
)
584 * save arguments if needed
587 ki
->ki_args
= getfmt(kvm_getargv
, ki
, KI_PROC(ki
, comm
),
593 ki
->ki_env
= getfmt(kvm_getenvv
, ki
, NULL
, 0);
600 pscomp(const void *arg_a
, const void *arg_b
)
602 const KINFO
*a
= *(KINFO
* const *)arg_a
;
603 const KINFO
*b
= *(KINFO
* const *)arg_b
;
608 #define VSIZE(k) (KI_PROC(k, vm_dsize) + KI_PROC(k, vm_ssize) + \
609 KI_PROC(k, vm_tsize))
612 if (sortby
== SORTIAC
)
613 return (KI_PROC(a
)->p_usdata
.bsd4
.interactive
- KI_PROC(b
)->p_usdata
.bsd4
.interactive
);
615 if (sortby
== SORTCPU
) {
616 di
= getpcpu(b
) - getpcpu(a
);
623 if (sortby
== SORTMEM
) {
624 si
= VSIZE(b
) - VSIZE(a
);
631 i
= KI_PROC(a
, tdev
) - KI_PROC(b
, tdev
);
633 i
= KI_PROC(a
, pid
) - KI_PROC(b
, pid
);
638 * Chain (-R) option. Sub-sorts by parent/child association.
640 static int dochain_final(KINFO
**kfinal
, KINFO
*base
, int j
);
643 dochain (KINFO
**ksort
, int *nentriesp
, pid_t pid
)
645 int nentries
= *nentriesp
;
655 * First hash all the pids so we can quickly locate the
658 khash
= calloc(KHSIZE
, sizeof(KINFO
*));
659 kfinal
= calloc(nentries
, sizeof(KINFO
*));
661 for (i
= 0; i
< nentries
; ++i
) {
662 hi
= KI_PROC(ksort
[i
], pid
) & KHMASK
;
664 ksort
[i
]->ki_hnext
= khash
[hi
];
665 khash
[hi
] = ksort
[i
];
669 * Now run through the list and create the parent associations.
671 for (i
= 0; i
< nentries
; ++i
) {
672 ppid
= KI_PROC(ksort
[i
], ppid
);
674 if (ppid
<= 0 || KI_PROC(ksort
[i
], pid
) <= 0) {
677 for (scan
= khash
[ppid
& KHMASK
];
679 scan
= scan
->ki_hnext
) {
680 if (ppid
== KI_PROC(scan
, pid
))
685 ksort
[i
]->ki_parent
= scan
;
686 *scan
->ki_ctailp
= ksort
[i
];
687 scan
->ki_ctailp
= &ksort
[i
]->ki_cnext
;
692 * Now regenerate the list starting at root entries, then copyback.
694 for (i
= j
= 0; i
< nentries
; ++i
) {
695 if (pid
!= (pid_t
)-1) {
696 if (KI_PROC(ksort
[i
], pid
) == pid
) {
697 ksort
[i
]->ki_indent
= 0;
698 j
= dochain_final(kfinal
, ksort
[i
], j
);
700 } else if (ksort
[i
]->ki_parent
== NULL
) {
701 ksort
[i
]->ki_indent
= 0;
702 j
= dochain_final(kfinal
, ksort
[i
], j
);
707 * There might be fewer entries if we restricted the chain to a
711 *nentriesp
= nentries
;
714 bcopy(kfinal
, ksort
, nentries
* sizeof(kfinal
[0]));
720 dochain_final(KINFO
**kfinal
, KINFO
*base
, int j
)
725 for (scan
= base
->ki_cbase
; scan
; scan
= scan
->ki_cnext
) {
729 if (scan
->ki_indent
>= 0)
731 scan
->ki_indent
= base
->ki_indent
+ 1;
732 j
= dochain_final(kfinal
, scan
, j
);
738 * ICK (all for getopt), would rather hide the ugliness
739 * here than taint the main code.
744 * The old convention that 't' with no trailing tty arg means the users
745 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
746 * feature is available with the option 'T', which takes no argument.
749 kludge_oldps_options(char *s
)
752 char *newopts
, *ns
, *cp
;
755 if ((newopts
= ns
= malloc(len
+ 2)) == NULL
)
758 * options begin with '-'
761 *ns
++ = '-'; /* add option flag */
764 * gaze to end of argv[1]
769 * if last letter is a 't' flag with no argument (in the context
770 * of the oldps options -- option string NOT starting with a '-' --
771 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
773 * However, if a flag accepting a string argument is found in the
774 * option string, the remainder of the string is the argument to
775 * that flag; do not modify that argument.
777 if (strcspn(s
, "MNOoU") == len
&& *cp
== 't' && *s
!= '-') {
781 * otherwise check for trailing number, which *may* be a
784 while (cp
>= s
&& isdigit(*cp
))
788 memmove(ns
, s
, (size_t)(cp
- s
)); /* copy up to trailing number */
791 * if there's a trailing number, and not a preceding 'p' (pid) or
792 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
795 (cp
== s
|| (cp
[-1] != 't' && cp
[-1] != 'p')) &&
796 (cp
- 1 == s
|| cp
[-2] != 't')) {
799 strcpy(ns
, cp
); /* and append the number */
809 if (statfs("/proc", &mnt
) < 0)
811 if (strcmp(mnt
.f_fstypename
, "procfs") != 0)
820 fprintf(stderr
, "%s\n%s\n%s\n",
821 "usage: ps [-aCcefhHjlmrSTuvwx] [-M core] [-N system] [-O fmt] [-o fmt] [-p pid]",
822 " [-t tty] [-U username]",