⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 viewproc.c

📁 使用读取/proc文件系统方法实现打印进程树。 2.6.26通过。
💻 C
字号:
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define MAX_LEN 16

struct proc_struct
{
	char name[MAX_LEN];//name
	int pid;//ID
	int ppid;//parent ID
	int flag;//printed or not
	struct proc_struct * next;//next process
};
typedef struct proc_struct* proc_pointer;

int get_num(proc_pointer p)
{
	proc_pointer temp = p;
	int num = 0;
	while(temp != NULL)
	{
		num ++;
		temp = temp->next;
	}
	return num;
}

void travel(proc_pointer head, proc_pointer p, int t)
{	int k, count = 0;
	for(k=0; k<t+1; k++)
		printf(" ");
	printf("|-%s-",p->name);
	p->flag = 0;
	proc_pointer temp = head->next;
	while(temp != NULL){
		if(temp->ppid == p->pid && temp->flag){
			count ++;
			printf("\n");
			travel(head, temp, t+strlen(p->name)+2);
		}
		temp = temp->next;
	}
	if(count == 0)
	printf("\b");
}
int isdigit(char *a)//"segmentation fault" if i directly use libs 
{	
	int i;
	for(i = 0; a[i]!='\0'; i++)
		if(a[i] <'0' || a[i] > '9') return 0;
	return 1;
}
int main(void)
{
	int i=0,n=0;
	char buff[MAX_LEN];
	char name[MAX_LEN];
	char dir[20];
	char data[10];
	DIR * dirproc;
	FILE * fp;
	proc_pointer p = NULL;
	proc_pointer proc_list_head = NULL;
	struct dirent * dirp;
	dirproc=opendir("/proc");//open the filesystem
	while(dirp = readdir(dirproc))//read the DIR , ie , the openned /proc
	{
		if(isdigit(dirp->d_name)==1)//dir name is a number
		{
			proc_pointer temp = (struct proc_struct *)malloc(sizeof(struct proc_struct));
			if(temp != NULL)//allocate memory successfully
			{
				temp->ppid = -1;
				temp->pid = atoi(dirp->d_name);//string to int
				temp->flag=1;
				if(proc_list_head == NULL)//the first process
				{
					proc_list_head = p = temp;
				}
				else
				{
					p->next = temp;
					p = p->next;
				}
				p->next = NULL;
			}
		}
	}
	closedir(dirproc);//end of accquiring the processes
	p=proc_list_head;
	while(p!= NULL)
	{
		memset(dir,0,20);
		memset(data,0,10);
		strcat(dir,"/proc/");
		sprintf(data,"%d/",p->pid);//give the data the proc name
		strcat(dir,data);//connect
		chdir(dir);//change dir to the certain proc dir
		fp =fopen("status","r");
		if(fp == NULL)
		{
			perror("open file \"status\" fail\n");
			return -1;
		}
		while(fgets(buff,MAX_LEN-1,fp))
		{
			if(strstr(buff,"Name:"))//reading Name section
			{
				sscanf(buff,"%s %s",name,p->name);
				//printf(name);
			}else
			if(strstr(buff,"PPid:"))//ppid section
			{
				sscanf(buff,"%s %d",name,&(p->ppid));
				//printf(buff);
			}
			memset(buff,0,MAX_LEN);
			memset(name,0,MAX_LEN);
		}
    	fclose(fp);
		p = p->next;
	}
	p=proc_list_head;
	n=get_num(p);
	travel(p, p, 0);
	printf("\n");
return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -