top.c revision 261ed7551e3234aa437658796afdc4eb372da9d7
1/*
2 * Copyright (c) 2008, The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *  * Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 *  * Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in
12 *    the documentation and/or other materials provided with the
13 *    distribution.
14 *  * Neither the name of Google, Inc. nor the names of its contributors
15 *    may be used to endorse or promote products derived from this
16 *    software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
25 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
28 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#include <ctype.h>
33#include <dirent.h>
34#include <grp.h>
35#include <pwd.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <sys/types.h>
40#include <unistd.h>
41
42struct cpu_info {
43    long unsigned utime, ntime, stime, itime;
44    long unsigned iowtime, irqtime, sirqtime;
45};
46
47#define PROC_NAME_LEN 64
48#define THREAD_NAME_LEN 32
49
50struct proc_info {
51    struct proc_info *next;
52    pid_t pid;
53    pid_t tid;
54    uid_t uid;
55    gid_t gid;
56    char name[PROC_NAME_LEN];
57    char tname[THREAD_NAME_LEN];
58    char state;
59    long unsigned utime;
60    long unsigned stime;
61    long unsigned delta_utime;
62    long unsigned delta_stime;
63    long unsigned delta_time;
64    long vss;
65    long rss;
66    int num_threads;
67};
68
69struct proc_list {
70    struct proc_info **array;
71    int size;
72};
73
74#define die(...) { fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); }
75
76#define INIT_PROCS 50
77#define THREAD_MULT 8
78static struct proc_info **old_procs, **new_procs;
79static int num_old_procs, num_new_procs;
80static struct proc_info *free_procs;
81static int num_used_procs, num_free_procs;
82
83static int max_procs, delay, iterations, threads;
84
85static struct cpu_info old_cpu, new_cpu;
86
87static struct proc_info *alloc_proc(void);
88static void free_proc(struct proc_info *proc);
89static void read_procs(void);
90static int read_stat(char *filename, struct proc_info *proc);
91static void add_proc(int proc_num, struct proc_info *proc);
92static int read_cmdline(char *filename, struct proc_info *proc);
93static int read_status(char *filename, struct proc_info *proc);
94static void print_procs(void);
95static struct proc_info *find_old_proc(pid_t pid, pid_t tid);
96static void free_old_procs(void);
97static int (*proc_cmp)(const void *a, const void *b);
98static int proc_cpu_cmp(const void *a, const void *b);
99static int proc_vss_cmp(const void *a, const void *b);
100static int proc_rss_cmp(const void *a, const void *b);
101static int proc_thr_cmp(const void *a, const void *b);
102static int numcmp(long long a, long long b);
103static void usage(char *cmd);
104
105int top_main(int argc, char *argv[]) {
106    int i;
107
108    num_used_procs = num_free_procs = 0;
109
110    max_procs = 0;
111    delay = 3;
112    iterations = -1;
113    proc_cmp = &proc_cpu_cmp;
114    for (i = 1; i < argc; i++) {
115        if (!strcmp(argv[i], "-m")) {
116            if (i + 1 >= argc) {
117                fprintf(stderr, "Option -m expects an argument.\n");
118                usage(argv[0]);
119                exit(EXIT_FAILURE);
120            }
121            max_procs = atoi(argv[++i]);
122            continue;
123        }
124        if (!strcmp(argv[i], "-n")) {
125            if (i + 1 >= argc) {
126                fprintf(stderr, "Option -n expects an argument.\n");
127                usage(argv[0]);
128                exit(EXIT_FAILURE);
129            }
130            iterations = atoi(argv[++i]);
131            continue;
132        }
133        if (!strcmp(argv[i], "-d")) {
134            if (i + 1 >= argc) {
135                fprintf(stderr, "Option -d expects an argument.\n");
136                usage(argv[0]);
137                exit(EXIT_FAILURE);
138            }
139            delay = atoi(argv[++i]);
140            continue;
141        }
142        if (!strcmp(argv[i], "-s")) {
143            if (i + 1 >= argc) {
144                fprintf(stderr, "Option -s expects an argument.\n");
145                usage(argv[0]);
146                exit(EXIT_FAILURE);
147            }
148            ++i;
149            if (!strcmp(argv[i], "cpu")) { proc_cmp = &proc_cpu_cmp; continue; }
150            if (!strcmp(argv[i], "vss")) { proc_cmp = &proc_vss_cmp; continue; }
151            if (!strcmp(argv[i], "rss")) { proc_cmp = &proc_rss_cmp; continue; }
152            if (!strcmp(argv[i], "thr")) { proc_cmp = &proc_thr_cmp; continue; }
153            fprintf(stderr, "Invalid argument \"%s\" for option -s.\n", argv[i]);
154            exit(EXIT_FAILURE);
155        }
156        if (!strcmp(argv[i], "-t")) { threads = 1; continue; }
157        if (!strcmp(argv[i], "-h")) {
158            usage(argv[0]);
159            exit(EXIT_SUCCESS);
160        }
161        fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
162        usage(argv[0]);
163        exit(EXIT_FAILURE);
164    }
165
166    if (threads && proc_cmp == &proc_thr_cmp) {
167        fprintf(stderr, "Sorting by threads per thread makes no sense!\n");
168        exit(EXIT_FAILURE);
169    }
170
171    free_procs = NULL;
172
173    num_new_procs = num_old_procs = 0;
174    new_procs = old_procs = NULL;
175
176    read_procs();
177    while ((iterations == -1) || (iterations-- > 0)) {
178        old_procs = new_procs;
179        num_old_procs = num_new_procs;
180        memcpy(&old_cpu, &new_cpu, sizeof(old_cpu));
181        sleep(delay);
182        read_procs();
183        print_procs();
184        free_old_procs();
185    }
186
187    return 0;
188}
189
190static struct proc_info *alloc_proc(void) {
191    struct proc_info *proc;
192
193    if (free_procs) {
194        proc = free_procs;
195        free_procs = free_procs->next;
196        num_free_procs--;
197    } else {
198        proc = malloc(sizeof(*proc));
199        if (!proc) die("Could not allocate struct process_info.\n");
200    }
201
202    num_used_procs++;
203
204    return proc;
205}
206
207static void free_proc(struct proc_info *proc) {
208    proc->next = free_procs;
209    free_procs = proc;
210
211    num_used_procs--;
212    num_free_procs++;
213}
214
215#define MAX_LINE 256
216
217static void read_procs(void) {
218    DIR *proc_dir, *task_dir;
219    struct dirent *pid_dir, *tid_dir;
220    char filename[64];
221    FILE *file;
222    int proc_num;
223    struct proc_info *proc;
224    pid_t pid, tid;
225
226    int i;
227
228    proc_dir = opendir("/proc");
229    if (!proc_dir) die("Could not open /proc.\n");
230
231    new_procs = calloc(INIT_PROCS * (threads ? THREAD_MULT : 1), sizeof(struct proc_info *));
232    num_new_procs = INIT_PROCS * (threads ? THREAD_MULT : 1);
233
234    file = fopen("/proc/stat", "r");
235    if (!file) die("Could not open /proc/stat.\n");
236    fscanf(file, "cpu  %lu %lu %lu %lu %lu %lu %lu", &new_cpu.utime, &new_cpu.ntime, &new_cpu.stime,
237            &new_cpu.itime, &new_cpu.iowtime, &new_cpu.irqtime, &new_cpu.sirqtime);
238    fclose(file);
239
240    proc_num = 0;
241    while ((pid_dir = readdir(proc_dir))) {
242        if (!isdigit(pid_dir->d_name[0]))
243            continue;
244
245        pid = atoi(pid_dir->d_name);
246
247        struct proc_info cur_proc;
248
249        if (!threads) {
250            proc = alloc_proc();
251
252            proc->pid = proc->tid = pid;
253
254            sprintf(filename, "/proc/%d/stat", pid);
255            read_stat(filename, proc);
256
257            sprintf(filename, "/proc/%d/cmdline", pid);
258            read_cmdline(filename, proc);
259
260            sprintf(filename, "/proc/%d/status", pid);
261            read_status(filename, proc);
262
263            proc->num_threads = 0;
264        } else {
265            sprintf(filename, "/proc/%d/cmdline", pid);
266            read_cmdline(filename, &cur_proc);
267
268            sprintf(filename, "/proc/%d/status", pid);
269            read_status(filename, &cur_proc);
270
271            proc = NULL;
272        }
273
274        sprintf(filename, "/proc/%d/task", pid);
275        task_dir = opendir(filename);
276        if (!task_dir) continue;
277
278        while ((tid_dir = readdir(task_dir))) {
279            if (!isdigit(tid_dir->d_name[0]))
280                continue;
281
282            if (threads) {
283                tid = atoi(tid_dir->d_name);
284
285                proc = alloc_proc();
286
287                proc->pid = pid; proc->tid = tid;
288
289                sprintf(filename, "/proc/%d/task/%d/stat", pid, tid);
290                read_stat(filename, proc);
291
292                strcpy(proc->name, cur_proc.name);
293                proc->uid = cur_proc.uid;
294                proc->gid = cur_proc.gid;
295
296                add_proc(proc_num++, proc);
297            } else {
298                proc->num_threads++;
299            }
300        }
301
302        closedir(task_dir);
303
304        if (!threads)
305            add_proc(proc_num++, proc);
306    }
307
308    for (i = proc_num; i < num_new_procs; i++)
309        new_procs[i] = NULL;
310
311    closedir(proc_dir);
312}
313
314static int read_stat(char *filename, struct proc_info *proc) {
315    FILE *file;
316    char buf[MAX_LINE], *open_paren, *close_paren;
317    int res, idx;
318
319    file = fopen(filename, "r");
320    if (!file) return 1;
321    fgets(buf, MAX_LINE, file);
322    fclose(file);
323
324    /* Split at first '(' and last ')' to get process name. */
325    open_paren = strchr(buf, '(');
326    close_paren = strrchr(buf, ')');
327    if (!open_paren || !close_paren) return 1;
328
329    *open_paren = *close_paren = '\0';
330    strncpy(proc->tname, open_paren + 1, THREAD_NAME_LEN);
331    proc->tname[THREAD_NAME_LEN-1] = 0;
332
333    /* Scan rest of string. */
334    sscanf(close_paren + 1, " %c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
335                 "%lu %lu %*d %*d %*d %*d %*d %*d %*d %lu %ld",
336                 &proc->state, &proc->utime, &proc->stime, &proc->vss, &proc->rss);
337
338    return 0;
339}
340
341static void add_proc(int proc_num, struct proc_info *proc) {
342    int i;
343
344    if (proc_num >= num_new_procs) {
345        new_procs = realloc(new_procs, 2 * num_new_procs * sizeof(struct proc_info *));
346        if (!new_procs) die("Could not expand procs array.\n");
347        for (i = num_new_procs; i < 2 * num_new_procs; i++)
348            new_procs[i] = NULL;
349        num_new_procs = 2 * num_new_procs;
350    }
351    new_procs[proc_num] = proc;
352}
353
354static int read_cmdline(char *filename, struct proc_info *proc) {
355    FILE *file;
356    char line[MAX_LINE];
357
358    line[0] = '\0';
359    file = fopen(filename, "r");
360    if (!file) return 1;
361    fgets(line, MAX_LINE, file);
362    fclose(file);
363    if (strlen(line) > 0) {
364        strncpy(proc->name, line, PROC_NAME_LEN);
365        proc->name[PROC_NAME_LEN-1] = 0;
366    } else
367        proc->name[0] = 0;
368    return 0;
369}
370
371static int read_status(char *filename, struct proc_info *proc) {
372    FILE *file;
373    char line[MAX_LINE];
374    unsigned int uid, gid;
375
376    file = fopen(filename, "r");
377    if (!file) return 1;
378    while (fgets(line, MAX_LINE, file)) {
379        sscanf(line, "Uid: %u", &uid);
380        sscanf(line, "Gid: %u", &gid);
381    }
382    fclose(file);
383    proc->uid = uid; proc->gid = gid;
384    return 0;
385}
386
387static void print_procs(void) {
388    int i;
389    struct proc_info *old_proc, *proc;
390    long unsigned total_delta_time;
391    struct passwd *user;
392    struct group *group;
393    char *user_str, user_buf[20];
394    char *group_str, group_buf[20];
395
396    for (i = 0; i < num_new_procs; i++) {
397        if (new_procs[i]) {
398            old_proc = find_old_proc(new_procs[i]->pid, new_procs[i]->tid);
399            if (old_proc) {
400                new_procs[i]->delta_utime = new_procs[i]->utime - old_proc->utime;
401                new_procs[i]->delta_stime = new_procs[i]->stime - old_proc->stime;
402            } else {
403                new_procs[i]->delta_utime = 0;
404                new_procs[i]->delta_stime = 0;
405            }
406            new_procs[i]->delta_time = new_procs[i]->delta_utime + new_procs[i]->delta_stime;
407        }
408    }
409
410    total_delta_time = (new_cpu.utime + new_cpu.ntime + new_cpu.stime + new_cpu.itime
411                        + new_cpu.iowtime + new_cpu.irqtime + new_cpu.sirqtime)
412                     - (old_cpu.utime + old_cpu.ntime + old_cpu.stime + old_cpu.itime
413                        + old_cpu.iowtime + old_cpu.irqtime + old_cpu.sirqtime);
414
415    qsort(new_procs, num_new_procs, sizeof(struct proc_info *), proc_cmp);
416
417    printf("\n\n\n");
418    printf("User %ld%%, System %ld%%, IOW %ld%%, IRQ %ld%%\n",
419            ((new_cpu.utime + new_cpu.ntime) - (old_cpu.utime + old_cpu.ntime)) * 100  / total_delta_time,
420            ((new_cpu.stime ) - (old_cpu.stime)) * 100 / total_delta_time,
421            ((new_cpu.iowtime) - (old_cpu.iowtime)) * 100 / total_delta_time,
422            ((new_cpu.irqtime + new_cpu.sirqtime)
423                    - (old_cpu.irqtime + old_cpu.sirqtime)) * 100 / total_delta_time);
424    printf("User %ld + Nice %ld + Sys %ld + Idle %ld + IOW %ld + IRQ %ld + SIRQ %ld = %ld\n",
425            new_cpu.utime - old_cpu.utime,
426            new_cpu.ntime - old_cpu.ntime,
427            new_cpu.stime - old_cpu.stime,
428            new_cpu.itime - old_cpu.itime,
429            new_cpu.iowtime - old_cpu.iowtime,
430            new_cpu.irqtime - old_cpu.irqtime,
431            new_cpu.sirqtime - old_cpu.sirqtime,
432            total_delta_time);
433    printf("\n");
434    if (!threads)
435        printf("%5s %4s %1s %5s %7s %7s %-8s %s\n", "PID", "CPU%", "S", "#THR", "VSS", "RSS", "UID", "Name");
436    else
437        printf("%5s %5s %4s %1s %7s %7s %-8s %-15s %s\n", "PID", "TID", "CPU%", "S", "VSS", "RSS", "UID", "Thread", "Proc");
438
439    for (i = 0; i < num_new_procs; i++) {
440        proc = new_procs[i];
441
442        if (!proc || (max_procs && (i >= max_procs)))
443            break;
444        user  = getpwuid(proc->uid);
445        group = getgrgid(proc->gid);
446        if (user && user->pw_name) {
447            user_str = user->pw_name;
448        } else {
449            snprintf(user_buf, 20, "%d", proc->uid);
450            user_str = user_buf;
451        }
452        if (group && group->gr_name) {
453            group_str = group->gr_name;
454        } else {
455            snprintf(group_buf, 20, "%d", proc->gid);
456            group_str = group_buf;
457        }
458        if (!threads)
459            printf("%5d %3ld%% %c %5d %6ldK %6ldK %-8.8s %s\n", proc->pid, proc->delta_time * 100 / total_delta_time, proc->state, proc->num_threads,
460                proc->vss / 1024, proc->rss * getpagesize() / 1024, user_str, proc->name[0] != 0 ? proc->name : proc->tname);
461        else
462            printf("%5d %5d %3ld%% %c %6ldK %6ldK %-8.8s %-15s %s\n", proc->pid, proc->tid, proc->delta_time * 100 / total_delta_time, proc->state,
463                proc->vss / 1024, proc->rss * getpagesize() / 1024, user_str, proc->tname, proc->name);
464    }
465}
466
467static struct proc_info *find_old_proc(pid_t pid, pid_t tid) {
468    int i;
469
470    for (i = 0; i < num_old_procs; i++)
471        if (old_procs[i] && (old_procs[i]->pid == pid) && (old_procs[i]->tid == tid))
472            return old_procs[i];
473
474    return NULL;
475}
476
477static void free_old_procs(void) {
478    int i;
479
480    for (i = 0; i < num_old_procs; i++)
481        if (old_procs[i])
482            free_proc(old_procs[i]);
483
484    free(old_procs);
485}
486
487static int proc_cpu_cmp(const void *a, const void *b) {
488    struct proc_info *pa, *pb;
489
490    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
491
492    if (!pa && !pb) return 0;
493    if (!pa) return 1;
494    if (!pb) return -1;
495
496    return -numcmp(pa->delta_time, pb->delta_time);
497}
498
499static int proc_vss_cmp(const void *a, const void *b) {
500    struct proc_info *pa, *pb;
501
502    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
503
504    if (!pa && !pb) return 0;
505    if (!pa) return 1;
506    if (!pb) return -1;
507
508    return -numcmp(pa->vss, pb->vss);
509}
510
511static int proc_rss_cmp(const void *a, const void *b) {
512    struct proc_info *pa, *pb;
513
514    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
515
516    if (!pa && !pb) return 0;
517    if (!pa) return 1;
518    if (!pb) return -1;
519
520    return -numcmp(pa->rss, pb->rss);
521}
522
523static int proc_thr_cmp(const void *a, const void *b) {
524    struct proc_info *pa, *pb;
525
526    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
527
528    if (!pa && !pb) return 0;
529    if (!pa) return 1;
530    if (!pb) return -1;
531
532    return -numcmp(pa->num_threads, pb->num_threads);
533}
534
535static int numcmp(long long a, long long b) {
536    if (a < b) return -1;
537    if (a > b) return 1;
538    return 0;
539}
540
541static void usage(char *cmd) {
542    fprintf(stderr, "Usage: %s [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]\n"
543                    "    -m num  Maximum number of processes to display.\n"
544                    "    -n num  Updates to show before exiting.\n"
545                    "    -d num  Seconds to wait between updates.\n"
546                    "    -s col  Column to sort by (cpu,vss,rss,thr).\n"
547                    "    -t      Show threads instead of processes.\n"
548                    "    -h      Display this help screen.\n",
549        cmd);
550}
551