C实现 list.c,尽量靠近STL::LIST

自用记录:

list.h

#ifndef __LIST_H__
#define __LIST_H__

#include "stdint.h"
#include <stdlib.h>
#include <string.h>

typedef struct _list
{
	struct _list *next;
	struct _list *prev;
	void *data;
}list;


typedef int (*date_compare)(void*,void*) ;

list *creat_list();

void delete_list(list *l);

int list_push_back(list *l,void *data,uint32_t data_size);
list * list_pop_back(list *l);

int list_push_front(list *l,void *data,uint32_t data_size);
list * list_pop_front(list *l);

/*
	date_compare(void*,void*) return 0 means find ok!
	return ok!=0,means find the 'data'!,user can not free the "ok"
*/
list* list_find(list *l,void *data,date_compare func);

list* list_remove(list *l,void *data,date_compare func);

list*  list_head(list *l);
list*  list_tail(list *l);

#endif

list.c 

#include "list.h"
#include <stdio.h>

#define MEM_CHECK	1
int g_mem_cnt=0;

void my_free(void *p)
{
	free(p);
	#if MEM_CHECK
	g_mem_cnt--;
	printf("g_mem_cnt=%d\n",g_mem_cnt);
	#endif
}

void* my_zalloc(uint32_t size)
{
	void *p = malloc(size);
	if(p!=NULL)
	{
		memset(p,0,size);
		#if MEM_CHECK
		g_mem_cnt++;
		printf("g_mem_cnt=%d\n",g_mem_cnt);
		#endif
	}
	return p;
}

list *creat_list()
{
	list *p;
	p = (list*)my_zalloc(sizeof(list));
	if(p!= NULL)
	{
		p->prev=NULL;
		p->next=NULL;
		p->data=NULL;
	}
	return p;
}

/*
	*l 可以 list中的任意一项,下同
*/
void delete_list(list *l)
{
	list *tmp=NULL;
	if(l==NULL)
	{
		return ;
	}
	
	list *head=l;
	while(head->prev!=NULL)
	{
		head = head->prev;
	}
	int i=0;
	while(head!=NULL)
	{		
		if(head->data)my_free(head->data);
		
		if(head->next== NULL)
		{
			my_free(head);
			break;
		}
		else
		{
			head = head->next;
			my_free(head->prev);
			head->prev = 0;
		}
	}
}

int list_push_back(list *l,void *data,uint32_t data_size)
{
	if(l==NULL || data==NULL)
	{
		return -1;
	}
	
	if(l->next==NULL && l->prev==NULL && l->data==NULL)
	{
		l->data = my_zalloc(data_size);
		if(l->data==NULL)
		{
			return -1;
		}
		memcpy(l->data,data,data_size);
		return 0;
	}
	
	list *p=(list*)my_zalloc(sizeof(list));
	if(p == NULL)
	{
		return -1;
	}
	memset(p,0,sizeof(list));
	
	p->data = my_zalloc(data_size);
	if(p->data==NULL)
	{
		my_free(p);
		return -1;
	}
	memcpy(p->data,data,data_size);
		
	list *tail=l;
	while(tail->next!=NULL)
	{
		tail = tail->next;
	}
	
	tail->next = p;
	p->prev = tail;
	
	return 0;
}

list *list_pop_back(list *l)
{
	if(l==NULL)
	{
		return NULL;
	}
	
	list *tail=l;
	while(tail->next!=NULL)
	{
		tail = tail->next;
	}
	
	if(tail->prev==NULL)//only 1 elemt
	{
		if(tail->data)my_free(tail->data);
		my_free(tail);
		tail = NULL;
	}
	else
	{
		tail = tail->prev;
		if(tail->data)my_free(tail->next->data);
		my_free(tail->next);
		tail->next = NULL;
	}
	
	return tail;
}

int list_push_front(list *l,void *data,uint32_t data_size)
{
	if(l==NULL || data==NULL)
	{
		return -1;
	}

	if(l->next==NULL && l->prev==NULL && l->data==NULL)
	{
		l->data = my_zalloc(data_size);
		if(l->data==NULL)
		{
			return -1;
		}
		memcpy(l->data,data,data_size);
		return 0;
	}
	
	list *p=(list*)my_zalloc(sizeof(list));
	if(p == NULL)
	{
		return -1;
	}
	
	p->data = my_zalloc(data_size);
	if(p->data==NULL)
	{
		my_free(p);
		return -1;
	}
	memcpy(p->data,data,data_size);
	
	list *head=l;	
	while(head->prev!=NULL)
	{
		head = head->prev;
	}
	
	head->prev = p;
	p->next = head;
	
	return 0;
}


list *  list_pop_front(list *l)
{
	if(l==NULL)
	{
		return NULL;
	}
	
	list *head=l;	
	while(head->prev!=NULL)
	{
		head = head->prev;
	}
	
	if(head->next==NULL)//only 1 elemt
	{
		if(head->data)my_free(head->data);
		my_free(head);
		head = NULL;
	}
	else
	{
		head = head->next;
		if(head->data)my_free(head->prev->data);
		my_free(head->prev);
		head->prev = NULL;
	}
	return head;
}

/*
	date_compare(void *a,void *b); a == b return 0 ; a > b return 1 ;a < b return
	return 0:no found!
	NOTE:user can not free the "ok"
*/
list* list_find(list *l,void *data,date_compare func)
{
	list *ok=NULL;
	if(l==NULL || data==NULL)
	{
		return ok;
	}
	
	list *find=l;
	
	while(find!=NULL)
	{
		if(0==func(find->data,data))
		{
			ok = find;
			break;
		}
	}	
	return ok;
}

static list* list_del(list *l)
{
	list *ret = NULL;
	if(l==NULL)
	{
		return NULL;
	}
	

	if(l->next == NULL)
	{
		if(l->prev == NULL)
		{
			free(l->data);
			free(l);
			return NULL;
		}
		else
		{
			free(l->data);

			l = l->prev;
			l->next = NULL;
			ret = l;
		}
	}
	else
	{
		if(l->prev == NULL)
		{
			free(l->data);

			l = l->next;
			l->prev = NULL;
			ret = l;
		}
		else
		{
			free(l->data);

			l->next->prev = l->prev;
			l->prev->next = l->next;
			ret = l->prev;
			free(l);
		}
	}
	return ret;
}

list* list_remove(list *l,void *data,date_compare func)
{
	list *e = list_find(l,data,func);
	if(e==NULL)//没找到
		return l;

	return list_del(e);
}

list*  list_head(list *l)
{
	list *head=NULL;
	if(l==NULL)
	{
		return head;
	}
	
	head=l;	
	while(head->prev!=NULL)
	{
		head = head->prev;
	}	
	
	return head;
}

list*  list_tail(list *l)
{
	list *tail=NULL;
	if(l==NULL)
	{
		return tail;
	}
	
	tail=l;	
	while(tail->next!=NULL)
	{
		tail = tail->next;
	}	
	return tail;
}


main.c 包含了检查进程以及线程的状态信息

#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <netdb.h>
#include <setjmp.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <memory.h>

#include "list.h"


char* safe_strncpy(char *dst, const char *src, size_t size)
{
	if (!size) return dst;
	dst[--size] = '\0';
	return strncpy(dst, src, size);
}

enum { COMM_LEN = 16 };
#define CMD_SIZE 64
typedef struct {
	DIR *dir;
	uint8_t shift_pages_to_bytes;
	uint8_t shift_pages_to_kb;
/* Fields are set to 0/NULL if failed to determine (or not requested) */
	uint16_t argv_len;
	/* Everything below must contain no ptrs to malloc'ed data:
	 * it is memset(0) for each process in procps_scan() */
	unsigned long vsz, rss; /* we round it to kbytes */
	unsigned long stime, utime;
	unsigned long start_time;
	unsigned pid;
	unsigned ppid;
	unsigned pgid;
	unsigned sid;
	unsigned uid;
	unsigned gid;

	unsigned tty_major,tty_minor;

	char state[4];
	char comm[COMM_LEN];
	char argv0[CMD_SIZE];
} procps_status_t;


#define PROCPS_BUFSIZE 1024

static int read_to_buf(const char *filename, void *buf)
{
	int fd;
	ssize_t ret = -1;
	fd = open(filename, O_RDONLY);
	if (fd >= 0) {
		ret = read(fd, buf, PROCPS_BUFSIZE-1);
		close(fd);
	}
	((char *)buf)[ret > 0 ? ret : 0] = '\0';
	return ret;
}

typedef struct          //定义一个cpu occupy的结构体
{
    char name[20];                  //定义一个char类型的数组名name有20个元素
    unsigned int user;              //定义一个无符号的int类型的user
    unsigned int nice;              //定义一个无符号的int类型的nice
    unsigned int system;            //定义一个无符号的int类型的system
    unsigned int idle;              //定义一个无符号的int类型的idle
    unsigned int iowait;
    unsigned int irq;
    unsigned int softirq;
}cpu_occupy_t;

int get_CPU(cpu_occupy_t *cpu)
{
	int n=0;
    char buf[PROCPS_BUFSIZE];
	char *filename="/proc/stat";
	n = read_to_buf(filename, buf);
	if(n<0)
	{
		printf("err_line=%d,filename=%s\n",__LINE__,filename);
		return -1;
	}
 
    n = sscanf (buf, "%s %u %u %u %u %u %u %u", cpu->name, &cpu->user, &cpu->nice,&cpu->system, &cpu->idle ,&cpu->iowait,&cpu->irq,&cpu->softirq);
	if(n < 8)
	{
		printf("err_lin=%d,filename=%s\n",__LINE__,filename);
		return -1;
	}
	
	printf("user=%u nice=%d system=%d idle=%d\n",cpu->user,cpu->nice,cpu->system,cpu->idle);
	return 0;
}

/*
打印进程内存情况和CPU情况, 以及每个子线程(如果存在)
*/

int  get_threadCPU(procps_status_t* sp,char *filename,char *filename_tail,char flag)
{	
	int n=0;
	char *cp, *comm1;
	int tty;
	unsigned long vsz, rss;
	long tasknice;
	char buf[PROCPS_BUFSIZE];
	
	strcpy(filename_tail, "stat");
	//printf("filename_tail=%s\n",filename);
	n = read_to_buf(filename, buf);
	if(n<0)
	{
		printf("err_lin=%d,filename=%s\n",__LINE__,filename);
		return -1;
	}
	cp = strchr(buf,')');
	cp[0] = '\0';
	
	comm1 = strchr(buf,'(');
	
	safe_strncpy(sp->comm, comm1 + 1, sizeof(sp->comm));
	//printf("cp=%s\n",cp+2);
	n = sscanf(cp+2,
		"%c %u "               /* state, ppid */
		"%u %u %d %*s "        /* pgid, sid, tty, tpgid */
		"%*s %*s %*s %*s %*s " /* flags, min_flt, cmin_flt, maj_flt, cmaj_flt */
		"%lu %lu "             /* utime, stime */
		"%*s %*s %*s "         /* cutime, cstime, priority */
		"%ld "                 /* nice */
		"%*s %*s "             /* timeout, it_real_value */
		"%lu "                 /* start_time */
		"%lu "                 /* vsize */
		"%lu "                 /* rss */
		,
		sp->state, &sp->ppid,
		&sp->pgid, &sp->sid, &tty,
		&sp->utime, &sp->stime,
		&tasknice,
		&sp->start_time,
		&vsz,
		&rss);
	if(n < 11)
	{
		printf("err_lin=%d,filename=%s\n",__LINE__,filename);
		return -1;
	}
	
	sp->vsz = vsz >> 10;
	sp->rss = rss << sp->shift_pages_to_kb;
	sp->tty_major = (tty >> 8) & 0xfff;
	sp->tty_minor = (tty & 0xff) | ((tty >> 12) & 0xfff00);	
	
	if(flag & 0x01)
	{
		strcpy(filename_tail, "cmdline");
		n = read_to_buf(filename, buf);
		if(n<0)
		{
			printf("err_lin=%d,filename=%s\n",__LINE__,filename);
			return -1;
		}
		safe_strncpy(sp->argv0,buf,n>CMD_SIZE ? CMD_SIZE : n);
	}
	return 0;
}

int get_processCPU(uint32_t pid,list *my_list)
{
	char filename[sizeof("/proc/%u/task/%u/cmdline") + sizeof(int)*3 * 2];
	char *filename_tail=0;

	struct dirent *entry;
	procps_status_t sp;
	cpu_occupy_t cpu;
	
	unsigned p_size = getpagesize();
	while (1) {
		p_size >>= 1;
		if (!p_size) break;
		sp.shift_pages_to_bytes++;
	}
	sp.shift_pages_to_kb = sp.shift_pages_to_bytes - 10;
	
	//all cpu
	//get_CPU(&cpu);
	
	//all process
	filename_tail = filename + sprintf(filename, "/proc/%u/", pid);;
	if(get_threadCPU(&sp,filename,filename_tail,1)==0)
	{
		sp.pid = pid;			
		//printf("[%s]state=%C pid=%u utime=%lu stime=%lu vsz=%lu rss=%lu\n",
				//sp.argv0,sp.state[0],sp.pid,sp.utime,sp.stime,sp.vsz,sp.rss);	
		list_push_front(my_list,&sp,sizeof(sp));				
	}
	else
	{
		printf("err_lin=%d,get_threadCPU err\n",__LINE__);
		return -1;
	}


	//thread info
	sprintf(filename, "/proc/%u/task", pid);
	DIR *dir=opendir(filename);
	if(dir==NULL)
	{
		printf("err_lin=%d,filename=%s\n",__LINE__,filename);
		return -1;
	}
	
	for(;;)
	{
		entry = readdir(dir);
		if(entry==NULL)
			break;
		
		if( (0==strcmp(entry->d_name,".")) || (0==strcmp(entry->d_name,".."))  )
		{
		    continue;
		}
		
		if(entry->d_type == DT_DIR )
		{
			sp.pid = atoi(entry->d_name);
			if(sp.pid == pid)
				continue;
			filename_tail = filename + sprintf(filename, "/proc/%u/task/%s/", pid,entry->d_name);
			if(get_threadCPU(&sp,filename,filename_tail,0)==0)
			{						
				//printf("\t[%s]state=%C pid=%-6u utime=%-6lu stime=%-6lu\n",
				//sp.comm,sp.state[0],sp.pid,sp.utime,sp.stime);	

				list_push_front(my_list,&sp,sizeof(sp));				
			}
		}
	}	
	closedir(dir);

	
}

/*
*/
void test01(uint32_t pid)
{
	list *my_list = creat_list();
	get_processCPU(pid,my_list);

	printf("pid=%d\n",pid);
	
	procps_status_t *sp;
	list *itr = list_head(my_list);
	for(;itr!=NULL;itr=itr->next)
	{
		sp = (procps_status_t*)itr->data;
		if(sp == NULL)
			continue;
		if(sp->pid == pid)
		{
			printf("[%s]state=%C pid=%u utime=%lu stime=%lu vsz=%lu rss=%lu\n",
				sp->argv0,sp->state[0],sp->pid,sp->utime,sp->stime,sp->vsz,sp->rss);
		}
		else
		{
			printf("\t[%s]state=%C pid=%-6u utime=%-6lu stime=%-6lu\n",
				sp->comm,sp->state[0],sp->pid,sp->utime,sp->stime);
		}
	}

	my_list=list_pop_back(my_list);

	my_list = list_pop_front(my_list);

	delete_list(my_list);
}

int main(int argc,char* argv[])
{
	
	uint32_t pid=0;

	if(argc>1)
	{
		pid = atoi(argv[1]);
	}

	uint32_t s_pid = getpid();

	if(pid==0)
		pid=s_pid;

	test01(pid);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值