#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
Linux下top命令底层源码Demo
最新推荐文章于 2023-01-27 13:42:06 发布
本文通过结合之前对top命令的深入解析,提供了一段自己编写的源码示例,旨在帮助读者更好地理解Linux系统中top命令的工作原理。
摘要由CSDN通过智能技术生成