/*
* Copyright (c) 2008, The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google, Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/

#include <ctype.h>
#include <dirent.h>
#include <grp.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

//#include <cutils/sched_policy.h>
/**
typedef enum {
SP_BACKGROUND = 0,
SP_FOREGROUND = 1,
} SchedPolicy;
*/
//extern int get_sched_policy(int tid, SchedPolicy *policy);

struct cpu_info {
long unsigned utime, ntime, stime, itime;
long unsigned iowtime, irqtime, sirqtime;
};

#define PROC_NAME_LEN 64
#define THREAD_NAME_LEN 32

struct proc_info {
struct proc_info *next;
pid_t pid;
pid_t tid;
uid_t uid;
gid_t gid;
char name[PROC_NAME_LEN];
char tname[THREAD_NAME_LEN];
char state;
long unsigned utime;
long unsigned stime;
long unsigned delta_utime;
long unsigned delta_stime;
long unsigned delta_time;
long vss;
long rss;
int num_threads;
char policy[32];
};

struct proc_list {
struct proc_info **array;
int size;
};

#define die(...) { fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); }

#define INIT_PROCS 50
#define THREAD_MULT 8
static struct proc_info **old_procs, **new_procs;
static int num_old_procs, num_new_procs;
static struct proc_info *free_procs;
static int num_used_procs, num_free_procs;

static int max_procs, delay, iterations, threads;

static struct cpu_info old_cpu, new_cpu;

static struct proc_info *alloc_proc(void);
static void free_proc(struct proc_info *proc);
static void read_procs(void);
static int read_stat(char *filename, struct proc_info *proc);
static void read_policy(int pid, struct proc_info *proc);
static void add_proc(int proc_num, struct proc_info *proc);
static int read_cmdline(char *filename, struct proc_info *proc);
static int read_status(char *filename, struct proc_info *proc);
static void print_procs(void);
static struct proc_info *find_old_proc(pid_t pid, pid_t tid);
static void free_old_procs(void);
static int (*proc_cmp)(const void *a, const void *b);
static int proc_cpu_cmp(const void *a, const void *b);
static int proc_vss_cmp(const void *a, const void *b);
static int proc_rss_cmp(const void *a, const void *b);
static int proc_thr_cmp(const void *a, const void *b);
static int numcmp(long long a, long long b);
static void usage(char *cmd);

int main(int argc, char *argv[]) {
int i;

num_used_procs = num_free_procs = 0;

max_procs = 0;
delay = 3;
iterations = -1;
proc_cmp = &proc_cpu_cmp;
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-m")) {
if (i + 1 >= argc) {
fprintf(stderr, "Option -m expects an argument.\n");
usage(argv[0]);
exit(EXIT_FAILURE);
}
max_procs = atoi(argv[++i]);
continue;
}
if (!strcmp(argv[i], "-n")) {
if (i + 1 >= argc) {
fprintf(stderr, "Option -n expects an argument.\n");
usage(argv[0]);
exit(EXIT_FAILURE);
}
iterations = atoi(argv[++i]);
continue;
}
if (!strcmp(argv[i], "-d")) {
if (i + 1 >= argc) {
fprintf(stderr, "Option -d expects an argument.\n");
usage(argv[0]);
exit(EXIT_FAILURE);
}
delay = atoi(argv[++i]);
continue;
}
if (!strcmp(argv[i], "-s")) {
if (i + 1 >= argc) {
fprintf(stderr, "Option -s expects an argument.\n");
usage(argv[0]);
exit(EXIT_FAILURE);
}
++i;
if (!strcmp(argv[i], "cpu")) { proc_cmp = &proc_cpu_cmp; continue; }
if (!strcmp(argv[i], "vss")) { proc_cmp = &proc_vss_cmp; continue; }
if (!strcmp(argv[i], "rss")) { proc_cmp = &proc_rss_cmp; continue; }
if (!strcmp(argv[i], "thr")) { proc_cmp = &proc_thr_cmp; continue; }
fprintf(stderr, "Invalid argument \"%s\" for option -s.\n", argv[i]);
exit(EXIT_FAILURE);
}
if (!strcmp(argv[i], "-t")) { threads = 1; continue; }
if (!strcmp(argv[i], "-h")) {
usage(argv[0]);
exit(EXIT_SUCCESS);
}
fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
usage(argv[0]);
exit(EXIT_FAILURE);
}

if (threads && proc_cmp == &proc_thr_cmp) {
fprintf(stderr, "Sorting by threads per thread makes no sense!\n");
exit(EXIT_FAILURE);
}

free_procs = NULL;

num_new_procs = num_old_procs = 0;
new_procs = old_procs = NULL;

read_procs();
while ((iterations == -1) || (iterations-- > 0)) {
old_procs = new_procs;
num_old_procs = num_new_procs;
memcpy(&old_cpu, &new_cpu, sizeof(old_cpu));
sleep(delay);
read_procs();
print_procs();
free_old_procs();
}

return 0;
}

static struct proc_info *alloc_proc(void) {
struct proc_info *proc;

if (free_procs) {
proc = free_procs;
free_procs = free_procs->next;
num_free_procs--;
} else {
proc = malloc(sizeof(*proc));
if (!proc) die("Could not allocate struct process_info.\n");
}

num_used_procs++;

return proc;
}

static void free_proc(struct proc_info *proc) {
proc->next = free_procs;
free_procs = proc;

num_used_procs--;
num_free_procs++;
}

#define MAX_LINE 256

static void read_procs(void) {
DIR *proc_dir, *task_dir;
struct dirent *pid_dir, *tid_dir;
char filename[64];
FILE *file;
int proc_num;
struct proc_info *proc;
pid_t pid, tid;

int i;

proc_dir = opendir("/proc");
if (!proc_dir) die("Could not open /proc.\n");

new_procs = calloc(INIT_PROCS * (threads ? THREAD_MULT : 1), sizeof(struct proc_info *));
num_new_procs = INIT_PROCS * (threads ? THREAD_MULT : 1);

file = fopen("/proc/stat", "r");
if (!file) die("Could not open /proc/stat.\n");
fscanf(file, "cpu %lu %lu %lu %lu %lu %lu %lu", &new_cpu.utime, &new_cpu.ntime, &new_cpu.stime,
&new_cpu.itime, &new_cpu.iowtime, &new_cpu.irqtime, &new_cpu.sirqtime);
fclose(file);

proc_num = 0;
while ((pid_dir = readdir(proc_dir))) {
if (!isdigit(pid_dir->d_name[0]))
continue;

pid = atoi(pid_dir->d_name);

struct proc_info cur_proc;

if (!threads) {
proc = alloc_proc();

proc->pid = proc->tid = pid;

sprintf(filename, "/proc/%d/stat", pid);
read_stat(filename, proc);

sprintf(filename, "/proc/%d/cmdline", pid);
read_cmdline(filename, proc);

sprintf(filename, "/proc/%d/status", pid);
read_status(filename, proc);

read_policy(pid, proc);

proc->num_threads = 0;
} else {
sprintf(filename, "/proc/%d/cmdline", pid);
read_cmdline(filename, &cur_proc);

sprintf(filename, "/proc/%d/status", pid);
read_status(filename, &cur_proc);

proc = NULL;
}

sprintf(filename, "/proc/%d/task", pid);
task_dir = opendir(filename);
if (!task_dir) continue;

while ((tid_dir = readdir(task_dir))) {
if (!isdigit(tid_dir->d_name[0]))
continue;

if (threads) {
tid = atoi(tid_dir->d_name);

proc = alloc_proc();

proc->pid = pid; proc->tid = tid;

sprintf(filename, "/proc/%d/task/%d/stat", pid, tid);
read_stat(filename, proc);

read_policy(tid, proc);

strcpy(proc->name, cur_proc.name);
proc->uid = cur_proc.uid;
proc->gid = cur_proc.gid;

add_proc(proc_num++, proc);
} else {
proc->num_threads++;
}
}

closedir(task_dir);

if (!threads)
add_proc(proc_num++, proc);
}

for (i = proc_num; i < num_new_procs; i++)
new_procs[i] = NULL;

closedir(proc_dir);
}

static int read_stat(char *filename, struct proc_info *proc) {
FILE *file;
char buf[MAX_LINE], *open_paren, *close_paren;
int res, idx;

file = fopen(filename, "r");
if (!file) return 1;
fgets(buf, MAX_LINE, file);
fclose(file);

/* Split at first '(' and last ')' to get process name. */
open_paren = strchr(buf, '(');
close_paren = strrchr(buf, ')');
if (!open_paren || !close_paren) return 1;

*open_paren = *close_paren = '\0';
strncpy(proc->tname, open_paren + 1, THREAD_NAME_LEN);
proc->tname[THREAD_NAME_LEN-1] = 0;

/* Scan rest of string. */
sscanf(close_paren + 1, " %c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
"%lu %lu %*d %*d %*d %*d %*d %*d %*d %lu %ld",
&proc->state, &proc->utime, &proc->stime, &proc->vss, &proc->rss);

return 0;
}

static void add_proc(int proc_num, struct proc_info *proc) {
int i;

if (proc_num >= num_new_procs) {
new_procs = realloc(new_procs, 2 * num_new_procs * sizeof(struct proc_info *));
if (!new_procs) die("Could not expand procs array.\n");
for (i = num_new_procs; i < 2 * num_new_procs; i++)
new_procs[i] = NULL;
num_new_procs = 2 * num_new_procs;
}
new_procs[proc_num] = proc;
}

static int read_cmdline(char *filename, struct proc_info *proc) {
FILE *file;
char line[MAX_LINE];

line[0] = '\0';
file = fopen(filename, "r");
if (!file) return 1;
fgets(line, MAX_LINE, file);
fclose(file);
if (strlen(line) > 0) {
strncpy(proc->name, line, PROC_NAME_LEN);
proc->name[PROC_NAME_LEN-1] = 0;
} else
proc->name[0] = 0;
return 0;
}

static void read_policy(int pid, struct proc_info *proc) {
/**
SchedPolicy p;
if (get_sched_policy(pid, &p) < 0)
strcpy(proc->policy, "unk");
else {
if (p == SP_BACKGROUND)
strcpy(proc->policy, "bg");
else if (p == SP_FOREGROUND)
strcpy(proc->policy, "fg");
else
strcpy(proc->policy, "er");
}*/
}

static int read_status(char *filename, struct proc_info *proc) {
FILE *file;
char line[MAX_LINE];
unsigned int uid, gid;

file = fopen(filename, "r");
if (!file) return 1;
while (fgets(line, MAX_LINE, file)) {
sscanf(line, "Uid: %u", &uid);
sscanf(line, "Gid: %u", &gid);
}
fclose(file);
proc->uid = uid; proc->gid = gid;
return 0;
}

static void print_procs(void) {
int i;
struct proc_info *old_proc, *proc;
long unsigned total_delta_time;
struct passwd *user;
struct group *group;
char *user_str, user_buf[20];
char *group_str, group_buf[20];

for (i = 0; i < num_new_procs; i++) {
if (new_procs[i]) {
old_proc = find_old_proc(new_procs[i]->pid, new_procs[i]->tid);
if (old_proc) {
new_procs[i]->delta_utime = new_procs[i]->utime - old_proc->utime;
new_procs[i]->delta_stime = new_procs[i]->stime - old_proc->stime;
} else {
new_procs[i]->delta_utime = 0;
new_procs[i]->delta_stime = 0;
}
new_procs[i]->delta_time = new_procs[i]->delta_utime + new_procs[i]->delta_stime;
}
}

total_delta_time = (new_cpu.utime + new_cpu.ntime + new_cpu.stime + new_cpu.itime
+ new_cpu.iowtime + new_cpu.irqtime + new_cpu.sirqtime)
- (old_cpu.utime + old_cpu.ntime + old_cpu.stime + old_cpu.itime
+ old_cpu.iowtime + old_cpu.irqtime + old_cpu.sirqtime);

qsort(new_procs, num_new_procs, sizeof(struct proc_info *), proc_cmp);

printf("\n\n\n");
printf("User %ld%%, System %ld%%, IOW %ld%%, IRQ %ld%%\n",
((new_cpu.utime + new_cpu.ntime) - (old_cpu.utime + old_cpu.ntime)) * 100 / total_delta_time,
((new_cpu.stime ) - (old_cpu.stime)) * 100 / total_delta_time,
((new_cpu.iowtime) - (old_cpu.iowtime)) * 100 / total_delta_time,
((new_cpu.irqtime + new_cpu.sirqtime)
- (old_cpu.irqtime + old_cpu.sirqtime)) * 100 / total_delta_time);
printf("User %ld + Nice %ld + Sys %ld + Idle %ld + IOW %ld + IRQ %ld + SIRQ %ld = %ld\n",
new_cpu.utime - old_cpu.utime,
new_cpu.ntime - old_cpu.ntime,
new_cpu.stime - old_cpu.stime,
new_cpu.itime - old_cpu.itime,
new_cpu.iowtime - old_cpu.iowtime,
new_cpu.irqtime - old_cpu.irqtime,
new_cpu.sirqtime - old_cpu.sirqtime,
total_delta_time);
printf("\n");
if (!threads)
printf("%5s %4s %1s %5s %7s %7s %3s %-8s %s\n", "PID", "CPU%", "S", "#THR", "VSS", "RSS", "PCY", "UID", "Name");
else
printf("%5s %5s %4s %1s %7s %7s %3s %-8s %-15s %s\n", "PID", "TID", "CPU%", "S", "VSS", "RSS", "PCY", "UID", "Thread", "Proc");

for (i = 0; i < num_new_procs; i++) {
proc = new_procs[i];

if (!proc || (max_procs && (i >= max_procs)))
break;
user = getpwuid(proc->uid);
group = getgrgid(proc->gid);
if (user && user->pw_name) {
user_str = user->pw_name;
} else {
snprintf(user_buf, 20, "%d", proc->uid);
user_str = user_buf;
}
if (group && group->gr_name) {
group_str = group->gr_name;
} else {
snprintf(group_buf, 20, "%d", proc->gid);
group_str = group_buf;
}
if (!threads)
printf("%5d %3ld%% %c %5d %6ldK %6ldK %3s %-8.8s %s\n", proc->pid, proc->delta_time * 100 / total_delta_time, proc->state, proc->num_threads,
proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy, user_str, proc->name[0] != 0 ? proc->name : proc->tname);
else
printf("%5d %5d %3ld%% %c %6ldK %6ldK %3s %-8.8s %-15s %s\n", proc->pid, proc->tid, proc->delta_time * 100 / total_delta_time, proc->state,
proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy, user_str, proc->tname, proc->name);
}
}

static struct proc_info *find_old_proc(pid_t pid, pid_t tid) {
int i;

for (i = 0; i < num_old_procs; i++)
if (old_procs[i] && (old_procs[i]->pid == pid) && (old_procs[i]->tid == tid))
return old_procs[i];

return NULL;
}

static void free_old_procs(void) {
int i;

for (i = 0; i < num_old_procs; i++)
if (old_procs[i])
free_proc(old_procs[i]);

free(old_procs);
}

static int proc_cpu_cmp(const void *a, const void *b) {
struct proc_info *pa, *pb;

pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);

if (!pa && !pb) return 0;
if (!pa) return 1;
if (!pb) return -1;

return -numcmp(pa->delta_time, pb->delta_time);
}

static int proc_vss_cmp(const void *a, const void *b) {
struct proc_info *pa, *pb;

pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);

if (!pa && !pb) return 0;
if (!pa) return 1;
if (!pb) return -1;

return -numcmp(pa->vss, pb->vss);
}

static int proc_rss_cmp(const void *a, const void *b) {
struct proc_info *pa, *pb;

pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);

if (!pa && !pb) return 0;
if (!pa) return 1;
if (!pb) return -1;

return -numcmp(pa->rss, pb->rss);
}

static int proc_thr_cmp(const void *a, const void *b) {
struct proc_info *pa, *pb;

pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);

if (!pa && !pb) return 0;
if (!pa) return 1;
if (!pb) return -1;

return -numcmp(pa->num_threads, pb->num_threads);
}

static int numcmp(long long a, long long b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}

static void usage(char *cmd) {
fprintf(stderr, "Usage: %s [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]\n"
" -m num Maximum number of processes to display.\n"
" -n num Updates to show before exiting.\n"
" -d num Seconds to wait between updates.\n"
" -s col Column to sort by (cpu,vss,rss,thr).\n"
" -t Show threads instead of processes.\n"
" -h Display this help screen.\n",
cmd);
}

linux top 源码分析的更多相关文章

  1. Linux内核源码分析--内核启动之(3)Image内核启动(C语言部分)(Linux-3.0 ARMv7)

    http://blog.chinaunix.net/uid-20543672-id-3157283.html Linux内核源码分析--内核启动之(3)Image内核启动(C语言部分)(Linux-3 ...

  2. Linux内核源码分析 day01——内存寻址

    前言 Linux内核源码分析 Antz系统编写已经开始了内核部分了,在编写时同时也参考学习一点Linux内核知识. 自制Antz操作系统 一个自制的操作系统,Antz .半图形化半命令式系统,同时嵌入 ...

  3. linux内存源码分析 - 零散知识点

    本文为原创,转载请注明:http://www.cnblogs.com/tolimit/ 直接内存回收中的等待队列 内存回收详解见linux内存源码分析 - 内存回收(整体流程),在直接内存回收过程中, ...

  4. linux内存源码分析 - 内存回收(整体流程)

    本文为原创,转载请注明:http://www.cnblogs.com/tolimit/ 概述 当linux系统内存压力就大时,就会对系统的每个压力大的zone进程内存回收,内存回收主要是针对匿名页和文 ...

  5. linux内存源码分析 - 内存压缩(同步关系)

    本文为原创,转载请注明:http://www.cnblogs.com/tolimit/ 概述 最近在看内存回收,内存回收在进行同步的一些情况非常复杂,然后就想,不会内存压缩的页面迁移过程中的同步关系也 ...

  6. linux内存源码分析 - 内存压缩(实现流程)

    本文为原创,转载请注明:http://www.cnblogs.com/tolimit/ 概述 本文章最好结合linux内存管理源码分析 - 页框分配器与linux内存源码分析 -伙伴系统(初始化和申请 ...

  7. linux内存源码分析 - SLUB分配器概述

    本文为原创,转载请注明:http://www.cnblogs.com/tolimit/ SLUB和SLAB的区别 首先为什么要说slub分配器,内核里小内存分配一共有三种,SLAB/SLUB/SLOB ...

  8. linux内存源码分析 - SLAB分配器概述【转】

    本文为原创,转载请注明:http://www.cnblogs.com/tolimit/ 之前说了管理区页框分配器,这里我们简称为页框分配器,在页框分配器中主要是管理物理内存,将物理内存的页框分配给申请 ...

  9. linux内存源码分析 - 伙伴系统(初始化和申请页框)

    本文为原创,转载请注明:http://www.cnblogs.com/tolimit/ 之前的文章已经介绍了伙伴系统,这篇我们主要看看源码中是如何初始化伙伴系统.从伙伴系统中分配页框,返回页框于伙伴系 ...

随机推荐

  1. C#动态调用WCF接口,两种方式任你选。

    写在前面 接触WCF还是它在最初诞生之处,一个分布式应用的巨作. 从开始接触到现在断断续续,真正使用的项目少之又少,更谈不上深入WCF内部实现机制和原理去研究,最近自己做一个项目时用到了WCF. 从这 ...

  2. 怎样使用My97日期控件

    有网友说无法使用My97日期控件,Insus.NET测试一下,是可以正常使用了. 在ASP.NET MVC环境中测试. 去官网下载My97日期控件程序包: 下载解压之后,把程序的目录拷贝至projec ...

  3. Post方式打开新窗口

    最近在做一个跟ERP相连的领料网站,用到POST的方法打开新窗口来打印报表 代码转别人的,在这里记一下: javascript代码 function openPostWindow(url, data1 ...

  4. 服务器Config文件不能查看的问题

      由于某种需求,需要从IIS发布的服务中下载扩展名为config的文件,但是发布文件后,在浏览器无法查看文件.根据反馈的的错误提示,大致说config属于配置文件,处于安全考虑,不能随便浏览. 如果 ...

  5. Spring注入中byType和byName的总结

    1.首先,区分清楚什么是byType,什么是byName. <bean id="userServiceImpl" class="cn.com.bochy.servi ...

  6. 初学C++ 之 auto关键字(IDE:VS2013)

    /*使用auto关键字,需要先赋初值,auto关键字是会根据初值来判断类型*/ auto i = ; auto j = ; cout << "auto i = 5" & ...

  7. 【JAVA并发编程实战】4、CountDownLatch

    这是一个计数锁,说白了,就是当你上锁的时候,只有计数减少到0的时候,才会释放锁 package cn.xf.cp.ch05; public class TaskRunable implements R ...

  8. Java基础学习 -- 接口

    interface是一种特殊的class 接口是纯抽象类 所有的成员函数都是抽象函数: 所有的成员变量都是public static final; 接口是为了方便类的调用 一个类如果要去实现某个接口, ...

  9. jquery限制文本框只能输入金额

    $("#batch_diff_percent").keyup(function () { var reg = $(this).val().match(/\d+\.?\d{0,2}/ ...

  10. jQuery ClockPicker 圆形时钟

    ClockPicker.js是一款时钟插件,其实还可以改进,里面的分可以改成短横线. 在线实例 实例预览  jQuery ClockPicker 圆形时钟 使用方法 <div class=&qu ...