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

📄 m_decosf1.c

📁 unix系统下top命令的源代码
💻 C
📖 第 1 页 / 共 2 页
字号:
		/*		 *  Place pointers to each valid proc structure in pref[].		 *  Process slots that are actually in use have a non-zero		 *  status field.  		 */#ifdef DEBUG		/*		 *  Emit debug info about all processes before selection.		 */		fprintf(stderr, "pid = %d ruid = %d comm = %s p_mach_state = %d p_stat = %d p_flag = 0x%x\n",			pp->p_pid, pp->p_ruid, p_i[k].pi_comm,			pp->p_mach_state, p_i[k].pi_status, pp->p_flag);#endif		if (pp->p_mach_state != 0)		{		    total_procs++;		    process_states[pp->p_mach_state]++;		    if ((pp->p_mach_state != 8) &&			(show_idle || (pp->p_mach_pct_cpu != 0) || 			 (pp->p_mach_state == 1)) &&			(!show_uid || pp->p_ruid == (uid_t)sel->uid)) {			*prefp++ = pp;			active_procs++;		    }		}	    }	}    }    /* if requested, sort the "interesting" processes */    if (compare != NULL)    {	qsort((char *)pref, active_procs, sizeof(struct osf1_top_proc *),                                                                     compare);    }    /* remember active and total counts */    si->p_total = total_procs;    si->p_active = pref_len = active_procs;    /* pass back a handle */    handle.next_proc = pref;    handle.remaining = active_procs;    return((caddr_t)&handle);}char fmt[128];		/* static area where result is built */char *format_next_process(handle, get_userid)caddr_t handle;char *(*get_userid)();{    register struct osf1_top_proc *pp;    register long cputime;    register double pct;    struct user u;    struct handle *hp;    /* find and remember the next proc structure */    hp = (struct handle *)handle;    pp = *(hp->next_proc++);    hp->remaining--;    /* get the process's user struct and set cputime */        if (table(TBL_UAREA,pp->p_pid,&u,1,sizeof(struct user))<0) {    /* whoops, it must have died between the read of the proc area     * and now. Oh well, lets just dump some meaningless thing out     * to keep the rest of the program happy     */	sprintf(fmt,		Proc_format,		pp->p_pid,		(*get_userid)(pp->p_ruid),		0,		0,		"",		"",		"dead",		"",		0.0,		"<dead>");	    return(fmt);    }    /* set u_comm for system processes */    if (u.u_comm[0] == '\0')    {	if (pp->p_pid == 0)	{	    (void) strcpy(u.u_comm, "[idle]");	}	else if (pp->p_pid == 2)	{	    (void) strcpy(u.u_comm, "[execpt.hndlr]");	}    }    /* Check if process is in core */    if (!(pp->p_flag & SLOAD)) {	/*	 * Print swapped processes as <pname>	 */	char buf[sizeof(u.u_comm)];	(void) strncpy(buf, u.u_comm, sizeof(u.u_comm));	u.u_comm[0] = '<';	(void) strncpy(&u.u_comm[1], buf, sizeof(u.u_comm) - 2);	u.u_comm[sizeof(u.u_comm) - 2] = '\0';	(void) strncat(u.u_comm, ">", sizeof(u.u_comm) - 1);	u.u_comm[sizeof(u.u_comm) - 1] = '\0';    }    cputime = u.u_ru.ru_utime.tv_sec + u.u_ru.ru_stime.tv_sec;    /* calculate the base for cpu percentages */    pct = pctdouble(pp->p_mach_pct_cpu);    /* format this entry */    sprintf(fmt,	    Proc_format,	    pp->p_pid,	    (*get_userid)(pp->p_ruid),	    pp->p_pri,	    pp->p_nice,            format_k(pp->p_mach_virt_size/1024),            format_k(pp->p_rssize/1000),	    state_abbrev[pp->p_mach_state],	    format_time(cputime),	    100.0 * ((double)pp->p_mach_pct_cpu / 10000.0),	    printable(u.u_comm));    /* return the result */    return(fmt);}/* *  getkval(offset, ptr, size, refstr) - get a value out of the kernel. *	"offset" is the byte offset into the kernel for the desired value, *  	"ptr" points to a buffer into which the value is retrieved, *  	"size" is the size of the buffer (and the object to retrieve), *  	"refstr" is a reference string used when printing error meessages, *	    if "refstr" starts with a '!', then a failure on read will not *  	    be fatal (this may seem like a silly way to do things, but I *  	    really didn't want the overhead of another argument). *  	 */getkval(offset, ptr, size, refstr)unsigned long offset;int *ptr;int size;char *refstr;{    if (lseek(kmem, (long)offset, L_SET) == -1) {        if (*refstr == '!')            refstr++;        (void) fprintf(stderr, "%s: lseek to %s: %s\n", KMEM, 		       refstr, strerror(errno));        quit(23);    }    if (read(kmem, (char *) ptr, size) == -1) {        if (*refstr == '!')             return(0);        else {            (void) fprintf(stderr, "%s: reading %s: %s\n", KMEM, 			   refstr, strerror(errno));            quit(23);        }    }    return(1);}    /* comparison routines for qsort *//* * There are currently four possible comparison routines.  main selects * one of these by indexing in to the array proc_compares. * * Possible keys are defined as macros below.  Currently these keys are * defined:  percent cpu, cpu ticks, process state, resident set size, * total virtual memory usage.  The process states are ordered as follows * (from least to most important):  WAIT, zomb, ???, halt, idle, sleep, * stop, run.  The array declaration below maps a process state index into * a number that reflects this ordering. *//* First, the possible comparison keys.  These are defined in such a way   that they can be merely listed in the source code to define the actual   desired ordering. */#define ORDERKEY_PCTCPU  if (lresult = p2->p_mach_pct_cpu - p1->p_mach_pct_cpu,\                           (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)#define ORDERKEY_CPTICKS if ((result = p2->used_ticks - p1->used_ticks) == 0)#define ORDERKEY_STATE   if ((result = sorted_state[p2->p_mach_state] - \                            sorted_state[p1->p_mach_state])  == 0)#define ORDERKEY_PRIO    if ((result = p2->p_pri - p1->p_pri) == 0)#define ORDERKEY_RSSIZE  if ((result = p2->p_rssize - p1->p_rssize) == 0)#define ORDERKEY_MEM     if ((result = p2->p_mach_virt_size - p1->p_mach_virt_size) == 0)/* Now the array that maps process state to a weight */static unsigned char sorted_state[] ={   0, /*""*/   8, /*"run"*/   1, /*"WAIT"*/   6, /*"sleep"*/   5, /*"idle"*/   7, /*"stop"*/   4, /*"halt"*/   3, /*"???"*/   2, /*"zomb"*/}; /* compare_cpu - the comparison function for sorting by cpu percentage */compare_cpu(pp1, pp2)struct osf1_top_proc **pp1;struct osf1_top_proc **pp2;{    register struct osf1_top_proc *p1;    register struct osf1_top_proc *p2;    register long result;    register pctcpu lresult;    /* remove one level of indirection */    p1 = *pp1;    p2 = *pp2;    ORDERKEY_PCTCPU    ORDERKEY_CPTICKS    ORDERKEY_STATE    ORDERKEY_PRIO    ORDERKEY_RSSIZE    ORDERKEY_MEM    ;    return(result);}/* compare_size - the comparison function for sorting by total memory usage */compare_size(pp1, pp2)struct osf1_top_proc **pp1;struct osf1_top_proc **pp2;{    register struct osf1_top_proc *p1;    register struct osf1_top_proc *p2;    register long result;    register pctcpu lresult;    /* remove one level of indirection */    p1 = *pp1;    p2 = *pp2;    ORDERKEY_MEM    ORDERKEY_RSSIZE    ORDERKEY_PCTCPU    ORDERKEY_CPTICKS    ORDERKEY_STATE    ORDERKEY_PRIO    ;    return(result);}/* compare_res - the comparison function for sorting by resident set size */compare_res(pp1, pp2)struct osf1_top_proc **pp1;struct osf1_top_proc **pp2;{    register struct osf1_top_proc *p1;    register struct osf1_top_proc *p2;    register long result;    register pctcpu lresult;    /* remove one level of indirection */    p1 = *pp1;    p2 = *pp2;    ORDERKEY_RSSIZE    ORDERKEY_MEM    ORDERKEY_PCTCPU    ORDERKEY_CPTICKS    ORDERKEY_STATE    ORDERKEY_PRIO    ;    return(result);}/* compare_time - the comparison function for sorting by total cpu time */compare_time(pp1, pp2)struct osf1_top_proc **pp1;struct osf1_top_proc **pp2;{    register struct osf1_top_proc *p1;    register struct osf1_top_proc *p2;    register long result;    register pctcpu lresult;    /* remove one level of indirection */    p1 = *pp1;    p2 = *pp2;    ORDERKEY_CPTICKS    ORDERKEY_PCTCPU    ORDERKEY_STATE    ORDERKEY_PRIO    ORDERKEY_RSSIZE    ORDERKEY_MEM    ;      return(result);}/* * proc_owner(pid) - returns the uid that owns process "pid", or -1 if *		the process does not exist. *		It is EXTREMLY IMPORTANT that this function work correctly. *		If top runs setuid root (as in SVR4), then this function *		is the only thing that stands in the way of a serious *		security problem.  It validates requests for the "kill" *		and "renice" commands. */int proc_owner(pid)int pid;{    register int cnt;    register struct osf1_top_proc **prefp;    register struct osf1_top_proc *pp;    prefp = pref;    cnt = pref_len;    while (--cnt >= 0)    {	if ((pp = *prefp++)->p_pid == (pid_t)pid)	{	    return((int)pp->p_ruid);	}    }    return(-1);}/* * We use the Mach interface, as well as the table(UAREA,,,) call to * get some more information, then put it into unused fields in our * copy of the proc structure, to make it faster and easier to get at * later. */void do_threads_calculations(thisproc)struct osf1_top_proc *thisproc; {  int j;  task_t  thistask;  task_basic_info_data_t   taskinfo;  unsigned int taskinfo_l;  thread_array_t    threadarr;  unsigned int threadarr_l;  thread_basic_info_t     threadinfo;  thread_basic_info_data_t threadinfodata;  unsigned int threadinfo_l;  int task_tot_cpu=0;  /* total cpu usage of threads in a task */  struct user u;  thisproc->p_pri=0;   thisproc->p_rssize=0;   thisproc->p_mach_virt_size=0;   thisproc->p_mach_state=0;   thisproc->p_mach_pct_cpu=0;  if(task_by_unix_pid(task_self(), thisproc->p_pid, &thistask)                                                 != KERN_SUCCESS){      thisproc->p_mach_state=8; /* (zombie) */  } else {    taskinfo_l=TASK_BASIC_INFO_COUNT;    if(task_info(thistask, TASK_BASIC_INFO, (task_info_t) &taskinfo,                                       &taskinfo_l)       != KERN_SUCCESS) {      thisproc->p_mach_state=8; /* (zombie) */    } else {      int minim_state=99,mcurp=1000,mbasp=1000,mslpt=999;      thisproc->p_rssize=taskinfo.resident_size;      thisproc->p_mach_virt_size=taskinfo.virtual_size;      (void) task_threads(thistask, &threadarr, &threadarr_l);      threadinfo= &threadinfodata;      for(j=0; j < threadarr_l; j++) {	threadinfo_l=THREAD_BASIC_INFO_COUNT;	if(thread_info(threadarr[j],THREAD_BASIC_INFO,	       (thread_info_t) threadinfo, &threadinfo_l) == KERN_SUCCESS) {	    	  task_tot_cpu += threadinfo->cpu_usage;	  if(minim_state>threadinfo->run_state)               minim_state=threadinfo->run_state;	  if(mcurp>threadinfo->cur_priority)               mcurp=threadinfo->cur_priority;	  if(mbasp>threadinfo->base_priority)               mbasp=threadinfo->base_priority;	  if(mslpt>threadinfo->sleep_time)               mslpt=threadinfo->sleep_time;	}      }      switch (minim_state) {      case TH_STATE_RUNNING:      	    thisproc->p_mach_state=1;  break;      case TH_STATE_UNINTERRUPTIBLE: 	    thisproc->p_mach_state=2; break;      case TH_STATE_WAITING:      	    thisproc->p_mach_state=(threadinfo->sleep_time > 20) ? 4 : 3; break;      case TH_STATE_STOPPED:      	    thisproc->p_mach_state=5; break;      case TH_STATE_HALTED:       	    thisproc->p_mach_state=6; break;      default:                    	    thisproc->p_mach_state=7; break;      }      thisproc->p_pri=mcurp;      thisproc->p_mach_pct_cpu=(fixpt_t)(task_tot_cpu*10);      vm_deallocate(task_self(),(vm_address_t)threadarr,threadarr_l);    }  }  if (table(TBL_UAREA,thisproc->p_pid,&u,1,sizeof(struct user))>=0) {    thisproc->used_ticks=(u.u_ru.ru_utime.tv_sec + u.u_ru.ru_stime.tv_sec);    thisproc->process_size=u.u_tsize + u.u_dsize + u.u_ssize;  }}/* The reason for this function is that the system call will let * someone lower their own processes priority (because top is setuid :-( * Yes, using syscall() is a hack, if you can come up with something  * better, then I'd be thrilled to hear it. I'm not holding my breath, * though.   *             Anthony. */int setpriority(int dummy, int procnum, int niceval){    int uid, curprio;    uid=getuid();    if ( (curprio=getpriority(PRIO_PROCESS,procnum) ) == -1)     {	return(-1); /* errno goes back to renice_process() */    }    /* check for not-root - if so, dont allow users to decrease priority */    else if ( uid && (niceval<curprio) )    {	errno=EACCES;	return(-1);    }    return(syscall(SYS_setpriority,PRIO_PROCESS,procnum,niceval));}

⌨️ 快捷键说明

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