- 论坛徽章:
- 0
|
回复 #1 jcs4989 的帖子
top命令源代码下载:http://www.groupsys.com/top/download.shtml
工程下载: http://www.cppblog.com/Files/dyj057/mytop.zip
下面是获得系统CPU和内存情况的代码:
void
get_system_info(info)
struct system_info * info;
{
char buffer[ 4096 + 1 ];
int fd, len;
char * p;
int i;
/* get load averages */
{
fd = open( " loadavg " , O_RDONLY);
len = read(fd, buffer, sizeof (buffer) - 1 );
close(fd);
buffer[len] = ' \0 ' ;
info -> load_avg[ 0 ] = strtod(buffer, & p);
info -> load_avg[ 1 ] = strtod(p, & p);
info -> load_avg[ 2 ] = strtod(p, & p);
p = skip_token(p); /* skip running/tasks */
p = skip_ws(p);
if ( * p)
info -> last_pid = atoi(p);
else
info -> last_pid = - 1 ;
}
/* get the cpu time info */
{
fd = open( " stat " , O_RDONLY);
len = read(fd, buffer, sizeof (buffer) - 1 );
close(fd);
buffer[len] = ' \0 ' ;
p = skip_token(buffer); /* "cpu" */
cp_time[ 0 ] = strtoul(p, & p, 0 );
cp_time[ 1 ] = strtoul(p, & p, 0 );
cp_time[ 2 ] = strtoul(p, & p, 0 );
cp_time[ 3 ] = strtoul(p, & p, 0 );
/* convert cp_time counts to percentages */
percentages( 4 , cpu_states, cp_time, cp_old, cp_diff);
}
/* get system wide memory usage */
{
char * p;
fd = open( " meminfo " , O_RDONLY);
len = read(fd, buffer, sizeof (buffer) - 1 );
close(fd);
buffer[len] = ' \0 ' ;
/* be prepared for extra columns to appear be seeking
to ends of lines */
p = buffer;
p = skip_token(p);
memory_stats[ 0 ] = strtoul(p, & p, 10 ); /* total memory */
p = strchr(p, ' \n ' );
p = skip_token(p);
memory_stats[ 1 ] = strtoul(p, & p, 10 ); /* free memory */
p = strchr(p, ' \n ' );
p = skip_token(p);
memory_stats[ 2 ] = strtoul(p, & p, 10 ); /* buffer memory */
p = strchr(p, ' \n ' );
p = skip_token(p);
memory_stats[ 3 ] = strtoul(p, & p, 10 ); /* cached memory */
for (i = 0 ; i < 8 ;i ++ ) {
p ++ ;
p = strchr(p, ' \n ' );
}
p = skip_token(p);
memory_stats[ 4 ] = strtoul(p, & p, 10 ); /* total swap */
p = strchr(p, ' \n ' );
p = skip_token(p);
memory_stats[ 5 ] = strtoul(p, & p, 10 ); /* free swap */
}
/* set arrays and strings */
info -> cpustates = cpu_states;
info -> memory = memory_stats;
}
原文地址 http://www.cppblog.com/dyj057/archive/2007/01/31/18221.aspx |
|