读取进程表 - Solaris

发表于:2007-05-26来源:作者:点击数: 标签:
怎样在程序中读取系统的进程表... #define _KMEMUSER #include sys/proc.h #include kvm.h #include fcntl.h char regexpstr[256]; #define INIT register char *sp=regexpstr; #define GETC() (*sp++) #define PEEKC() (*sp) #define UNGETC(c) (--sp) #def
怎样在程序中读取系统的进程表...

 #define _KMEMUSER
     #include <sys/proc.h>
     #include <kvm.h>
     #include <fcntl.h>
   
     char regexpstr[256];
     #define INIT            register char *sp=regexpstr;
     #define GETC()          (*sp++)
     #define PEEKC()         (*sp)
     #define UNGETC(c)       (--sp)
     #define RETURN(pointer) return(pointer);
     #define ERROR(val)
     #include <regexp.h>
  
     pid_t
     getpidbyname(char *name,pid_t skipit)
     {
         kvm_t *kd;
         char **arg;
         int error;
         char *p_name=NULL;
         char expbuf[256];
         char **freeme;
         int curpid;
         struct user * cur_user;
         struct user myuser;
         struct proc * cur_proc;
   
   
         if((kd=kvm_open(NULL,NULL,NULL,O_RDONLY,NULL))==NULL){
             return(-1);
         }
         sprintf(regexpstr,"^.*/%s$",name);
         compile(NULL,expbuf,expbuf+256,'');
   
         while(cur_proc=kvm_nextproc(kd)){
             curpid = cur_proc->p_pid;
             if((cur_user=kvm_getu(kd,cur_proc))!=NULL){
                 error=kvm_getcmd(kd,cur_proc,cur_user,&arg,NULL);
                 if(error==-1){
                     if(cur_user->u_comm[0]!=''){
                         p_name=cur_user->u_comm;
                     }
                 }
                 else{
                     p_name=arg[0];
                 }
             }
             if(p_name){
                 if(!strcmp(p_name,name)){
                     if(error!=-1){
                         free(arg);
                     }
                     if(skipit!=-1 && ourretval==skipit){
                         ourretval=-1;
                     }
                     else{
                         close(fd);
                         break;
                     }
                     break;
                 }
                 else{
                     if(step(p_name,expbuf)){
                         if(error!=-1){
                             free(arg);
                         }
                         break;
                     }
                 }
             }
             if(error!=-1){
                 free(arg);
             }
             p_name=NULL;
         }
         kvm_close(kd);
         if(p_name!=NULL){
             return(curpid);
         }
         return (-1);
     }

原文转自:http://www.ltesting.net