xref: /netbsd-src/usr.bin/systat/ps.c (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1 /*      $NetBSD: ps.c,v 1.36 2014/02/19 20:42:14 dsl Exp $  */
2 
3 /*-
4  * Copyright (c) 1999
5  *      The NetBSD Foundation, Inc.  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 NetBSD Foundation.
18  * 4. Neither the name of the Foundation nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * XXX Notes XXX
37  * showps -- print data needed at each refresh
38  * fetchps -- get data used by mode (done at each refresh)
39  * labelps -- print labels (ie info not needing refreshing)
40  * initps -- prepare once-only data structures for mode
41  * openps -- prepare per-run information for mode, return window
42  * closeps -- close mode to prepare to switch modes
43  * cmdps -- optional, handle commands
44  */
45 
46 #include <sys/cdefs.h>
47 #ifndef lint
48 __RCSID("$NetBSD: ps.c,v 1.36 2014/02/19 20:42:14 dsl Exp $");
49 #endif /* not lint */
50 
51 #include <sys/param.h>
52 #include <sys/sched.h>
53 #include <sys/sysctl.h>
54 
55 #include <curses.h>
56 #include <math.h>
57 #include <pwd.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <tzfile.h>
61 #include <unistd.h>
62 
63 #include "systat.h"
64 #include "extern.h"
65 #include "ps.h"
66 
67 int compare_pctcpu_noidle(const void *, const void *);
68 char *state2str(struct kinfo_proc2 *);
69 char *tty2str(struct kinfo_proc2 *);
70 int rss2int(struct kinfo_proc2 *);
71 int vsz2int(struct kinfo_proc2 *);
72 char *comm2str(struct kinfo_proc2 *);
73 double pmem2float(struct kinfo_proc2 *);
74 char *start2str(struct kinfo_proc2 *);
75 char *time2str(struct kinfo_proc2 *);
76 
77 static time_t now;
78 
79 #define SHOWUSER_ANY	(uid_t)-1
80 static uid_t showuser = SHOWUSER_ANY;
81 
82 #ifndef P_ZOMBIE
83 #define P_ZOMBIE(p)	((p)->p_stat == SZOMB)
84 #endif
85 
86 void
87 labelps(void)
88 {
89 	mvwaddstr(wnd, 0, 0, "USER      PID %CPU %MEM    VSZ   RSS TT  STAT STARTED       TIME COMMAND");
90 }
91 
92 void
93 showps(void)
94 {
95 	int i, k, y, vsz, rss;
96 	const char *user, *comm, *state, *tty, *start, *time_str;
97 	pid_t pid;
98 	double pctcpu, pctmem;
99 	struct kinfo_proc2 *kp;
100 
101 	now = 0;	/* force start2str to reget current time */
102 
103 	qsort(pt, nproc + 1, sizeof (struct p_times), compare_pctcpu_noidle);
104 
105 	y = 1;
106 	i = nproc + 1;
107 	if (i > getmaxy(wnd)-2)
108 		i = getmaxy(wnd)-1;
109 	for (k = 0; i > 0 ; k++) {
110 		if (pt[k].pt_kp == NULL) /* We're all the way down to the imaginary idle proc */
111 			break;
112 
113 		kp = pt[k].pt_kp;
114 		if (showuser != SHOWUSER_ANY && kp->p_uid != showuser)
115 			continue;
116 		user = user_from_uid(kp->p_uid, 0);
117 		pid = kp->p_pid;
118 		pctcpu = 100.0 * pt[k].pt_pctcpu;
119 		pctmem = pmem2float(pt[k].pt_kp);
120 		vsz = vsz2int(pt[k].pt_kp);
121 		rss = rss2int(pt[k].pt_kp);
122 		tty = tty2str(pt[k].pt_kp);
123 		state = state2str(pt[k].pt_kp);
124 		start = start2str(pt[k].pt_kp);
125 		time_str = time2str(pt[k].pt_kp);
126 		comm = comm2str(pt[k].pt_kp);
127 		/*comm = pt[k].pt_kp->kp_proc.p_comm; */
128 
129 		wmove(wnd, y, 0);
130 		wclrtoeol(wnd);
131 		mvwprintw(wnd, y++, 0,
132 		    "%-8.8s%5d %4.1f %4.1f %6d %5d %-3s %-4s %7s %10.10s %s",
133 		    user, pid, pctcpu, pctmem, vsz, rss, tty, state, start,
134 		    time_str, comm);
135 		i--;
136 	}
137 	wmove(wnd, y, 0);
138 	wclrtobot(wnd);
139 }
140 
141 int
142 compare_pctcpu_noidle(const void *a, const void *b)
143 {
144 	if (((const struct p_times *) a)->pt_kp == NULL)
145 		return 1;
146 
147 	if (((const struct p_times *) b)->pt_kp == NULL)
148 	 	return -1;
149 
150 	return (((const struct p_times *) a)->pt_pctcpu >
151 		((const struct p_times *) b)->pt_pctcpu)? -1: 1;
152 }
153 
154 /* from here down adapted from .../src/usr.bin/ps/print.c .  Any mistakes are my own, however. */
155 char *
156 state2str(struct kinfo_proc2 *kp)
157 {
158 	int flag;
159 	char *cp;
160 	char buf[5];
161 	static char statestr[4];
162 
163 	flag = kp->p_flag;
164 	cp = buf;
165 
166 	switch (kp->p_stat) {
167 	case LSSTOP:
168 		*cp = 'T';
169 		break;
170 
171 	case LSSLEEP:
172 		if (flag & L_SINTR)     /* interruptable (long) */
173 			*cp = kp->p_slptime >= (uint32_t)maxslp ? 'I' : 'S';
174 		else
175 			*cp = 'D';
176 		break;
177 
178 	case LSRUN:
179 	case LSIDL:
180 	case LSONPROC:
181 		*cp = 'R';
182 		break;
183 
184 	case LSZOMB:
185 #ifdef LSDEAD
186 	case LSDEAD:
187 #endif
188 		*cp = 'Z';
189 		break;
190 
191 	default:
192 		*cp = '?';
193 	}
194 	cp++;
195 	if (kp->p_nice < NZERO)
196 		*cp++ = '<';
197 	else if (kp->p_nice > NZERO)
198 		*cp++ = 'N';
199 	if (flag & P_TRACED)
200 		*cp++ = 'X';
201 	if (flag & P_WEXIT &&
202 	    /* XXX - I don't like this */
203 	    (kp->p_stat != LSZOMB))
204 		*cp++ = 'E';
205 	if (flag & P_PPWAIT)
206 		*cp++ = 'V';
207 	if (kp->p_eflag & EPROC_SLEADER)
208 		*cp++ = 's';
209 	if ((flag & P_CONTROLT) && kp->p__pgid == kp->p_tpgid)
210 		*cp++ = '+';
211 	*cp = '\0';
212 	snprintf(statestr, sizeof(statestr), "%-s",  buf);
213 
214 	return statestr;
215 }
216 
217 char *
218 tty2str(struct kinfo_proc2 *kp)
219 {
220 	static char ttystr[4];
221 	char *tty_name;
222 
223 	if (kp->p_tdev == (uint32_t)NODEV ||
224 	    (tty_name = devname(kp->p_tdev, S_IFCHR)) == NULL)
225 		strlcpy(ttystr, "??", sizeof(ttystr));
226 	else {
227 		if (strncmp(tty_name, "tty", 3) == 0 ||
228 		    strncmp(tty_name, "dty", 3) == 0)
229 			tty_name += 3;
230 		snprintf(ttystr, sizeof(ttystr), "%s%c", tty_name,
231 		    kp->p_eflag & EPROC_CTTY ? ' ' : '-');
232 	}
233 
234 	return ttystr;
235 }
236 
237 #define pgtok(a)	(((a)*getpagesize())/1024)
238 
239 int
240 vsz2int(struct kinfo_proc2 *kp)
241 {
242 	int     i;
243 
244 	i = pgtok(kp->p_vm_msize);
245 
246 	return ((i < 0) ? 0 : i);
247 }
248 
249 int
250 rss2int(struct kinfo_proc2 *kp)
251 {
252 	int	i;
253 
254 	i = pgtok(kp->p_vm_rssize);
255 
256 	/* XXX don't have info about shared */
257 	return ((i < 0) ? 0 : i);
258 }
259 
260 char *
261 comm2str(struct kinfo_proc2 *kp)
262 {
263 	char **argv;
264 	static char commstr[41];
265 
266 	commstr[0]='\0';
267 
268 	argv = kvm_getargv2(kd, kp, 40);
269 	if (argv != NULL) {
270 		while (*argv) {
271 			strlcat(commstr, *argv, sizeof(commstr));
272 			argv++;
273 			strlcat(commstr, " ", sizeof(commstr));
274 		}
275 	} else {
276 		const char *fmt;
277 
278 		/*
279 		 * Commands that don't set an argv vector are printed with
280 		 * square brackets if they are system commands.  Otherwise
281 		 * they are printed within parentheses.
282 		 */
283 		if (kp->p_flag & P_SYSTEM)
284 			fmt = "[]";
285 		else
286 			fmt = "()";
287 
288 		snprintf(commstr, sizeof(commstr), "%c%s%c", fmt[0],
289 		    kp->p_comm, fmt[1]);
290 	}
291 
292 	return commstr;
293 }
294 
295 double
296 pmem2float(struct kinfo_proc2 *kp)
297 {
298 	double fracmem;
299 	int szptudot = 0;
300 
301 #ifdef USPACE
302 	/* XXX want pmap ptpages, segtab, etc. (per architecture) */
303 	szptudot = USPACE/getpagesize();
304 #endif
305 	/* XXX don't have info about shared */
306 	fracmem = ((double)kp->p_vm_rssize + szptudot)/mempages;
307 	return (fracmem >= 0) ? 100.0 * fracmem : 0;
308 }
309 
310 char *
311 start2str(struct kinfo_proc2 *kp)
312 {
313 	struct timeval u_start;
314 	struct tm *tp;
315 	time_t startt;
316 	static char startstr[10];
317 
318 	u_start.tv_sec = kp->p_ustart_sec;
319 	u_start.tv_usec = kp->p_ustart_usec;
320 
321 	startt = u_start.tv_sec;
322 	tp = localtime(&startt);
323 	if (now == 0)
324 	        time(&now);
325 	if (now - u_start.tv_sec < 24 * SECSPERHOUR) {
326 		/* I *hate* SCCS... */
327 	        strftime(startstr, sizeof(startstr) - 1, "%l:%" "M%p", tp);
328 	} else if (now - u_start.tv_sec < 7 * SECSPERDAY) {
329 	        /* I *hate* SCCS... */
330 	        strftime(startstr, sizeof(startstr) - 1, "%a%" "I%p", tp);
331 	} else
332 	        strftime(startstr, sizeof(startstr) - 1, "%e%b%y", tp);
333 
334 	return startstr;
335 }
336 
337 char *
338 time2str(struct kinfo_proc2 *kp)
339 {
340 	long secs;
341 	long psecs;     /* "parts" of a second. first micro, then centi */
342 	static char timestr[10];
343 
344 	/* XXX - I don't like this. */
345 	if (kp->p_stat == SZOMB) {
346 	        secs = 0;
347 	        psecs = 0;
348 	} else {
349 	        /*
350 	         * This counts time spent handling interrupts.  We could
351 	         * fix this, but it is not 100% trivial (and interrupt
352 	         * time fractions only work on the sparc anyway).       XXX
353 	         */
354 	        secs = kp->p_rtime_sec;
355 	        psecs = kp->p_rtime_usec;
356 #if 0
357 	        if (sumrusage) {
358 	                secs += k->ki_u.u_cru.ru_utime.tv_sec +
359 	                        k->ki_u.u_cru.ru_stime.tv_sec;
360 	                psecs += k->ki_u.u_cru.ru_utime.tv_usec +
361 	                        k->ki_u.u_cru.ru_stime.tv_usec;
362 	        }
363 #endif
364 	        /*
365 	         * round and scale to 100's
366 	         */
367 	        psecs = (psecs + 5000) / 10000;
368 	        secs += psecs / 100;
369 	        psecs = psecs % 100;
370 	}
371 	snprintf(timestr, sizeof(timestr), "%3ld:%02ld.%02ld", secs/60,
372 	    secs%60, psecs);
373 
374 	return timestr;
375 }
376 
377 void
378 ps_user(char *args)
379 {
380 	uid_t uid;
381 
382 	if (args == NULL || *args == 0 || strcmp(args, "+") == 0) {
383 		uid = SHOWUSER_ANY;
384 	} else if (uid_from_user(args, &uid) != 0) {
385 		error("%s: unknown user", args);
386 		return;
387 	}
388 
389 	showuser = uid;
390 	display(0);
391 }
392