- 论坛徽章:
- 0
|
贴一个我以前写的吧,或许对你有点用。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#define NAME_SIZE 20
#define BUF_SIZE 50
struct proc_list{
pid_t pid;
pid_t ppid;
char name[NAME_SIZE];
char status;
struct proc_list *next;
};
struct proc_list *inport_list(char *);
void show_info(struct proc_list *);
int read_info(char *,struct proc_list *);
void free_list(struct proc_list *);
int is_num(char *);
int main()
{
struct proc_list *head = inport_list("/proc");
if(head==NULL){
printf("inport list failed !\n");
}
show_info(head);
free_list(head);
return 0;
}
struct proc_list *inport_list(char *dir){
DIR *dsptr;
struct dirent *dptr;
struct proc_list *head=NULL,*ptr=NULL;
if((dsptr=opendir(dir))==NULL){
printf("Error open the dir %s\n",dir);
exit(-1);
}
// read all the dir and file under directory "dir" ;
while((dptr=readdir(dsptr))!=NULL){
if(is_num(dptr->d_name)==0){ // determine if the d_name is a number ;
// request some memeory , some = sizeof(struct proc_list) ;
struct proc_list *item = (struct proc_list *)malloc(sizeof(struct proc_list));
if(item==NULL){
printf("memory allocate error !\n");
// must do some free() work here !
free_list(head);
exit(-1);
}
memset(item,0,sizeof(struct proc_list));
// link the item to proc_list list ;
if(head==NULL)
head=ptr=item;
else{
ptr->next=item;
ptr=ptr->next;
}
item->pid = atoi(dptr->d_name);
if(read_info(dptr->d_name,item)!=0){ // determine if read error occurred ;
// must do some free() work here ;
free_list(head);
exit(-1);
}
}
}
closedir(dsptr);
return head;
}
int read_info(char *d_name,struct proc_list *item){
char dir[20];
char name[NAME_SIZE];
char buffer[BUF_SIZE];
FILE *fptr;
sprintf(dir,"%s%s","/proc/",d_name);
chdir(dir);
fptr=fopen("status","r");
if(fptr==NULL){
printf("Error reading %s%s\n",dir,"status");
return -1;
}
while(fgets(buffer,BUF_SIZE-1,fptr))
{
if(strstr(buffer,"Name:")){
sscanf(buffer,"%s%s",name,item->name);
}else if(strstr(buffer,"PPid:")){
sscanf(buffer,"%s%d",name,&(item->ppid));
}else if(strstr(buffer,"State:")){
sscanf(buffer,"%s %c",name,&(item->status));
}
}
fclose(fptr);
return 0;
}
void free_list(struct proc_list *head){
struct proc_list *ptr;
while(head!=NULL){
ptr=head;
head=head->next;
free(ptr);
}
}
void show_info(struct proc_list *head){
struct proc_list *ptr;
printf("pid\tppid\tstatus\tname\n");
for(ptr=head;ptr!=NULL;ptr=ptr->next)
printf("%d\t%d\t%c\t%s\n",ptr->pid,ptr->ppid,ptr->status,ptr->name);
}
int is_num(char *d_name){
int i,size;
size = strlen(d_name);
if(size==0) return -1;
// determine if the dir name is number ;
for(i=0;i<size;i++)
if(d_name[i]<'0' || d_name[i]>'9') return -1;
return 0;
} |
|