Linux下top命令底层源码Demo

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

#define PROC_NAME_LEN 64
#define THREAD_NAME_LEN 32
#define MAX_LINE 256	
#define INIT_PROCS 50
#define THREAD_MULT 16

static struct proc_info **old_procs, **new_procs;
static struct proc_info *free_procs;
static struct cpu_info old_cpu, new_cpu;
static int num_old_procs, num_new_procs;
static int num_used_procs, num_free_procs;
static int threads;



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

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 prs;
	int nice;
	int num_threads;
	char policy[32];
};

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));
	}
	num_used_procs++;

	return proc;
}

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 *));
      
        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 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 int read_stat(const char *filename,struct proc_info *proc)
{
	FILE *file;
	char buf[MAX_LINE], *open_paren, *close_paren;
	int res, idx;

	fil
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值