在Linux中如果要监视一个进程的运行情况,如查看它的CPU使用效率和内存使用情况,就需要从系统的/proc目录的读取一些系统信息。然后分析得到结果,特别是在嵌入式中的应用程序这个功能就很重要。本文中的代码是从top命令的源代码分析中获得,并做了部分修改,在FC6+GCC4.1调试通过。从这个工程中我也获得一些感悟。
1. Linux系统很优雅,如果在Windows中做这个功能就需要调用ActiveX控件。而在Linux中只需要读取文本。
2.想完成什么功能,如果不知道怎么做,就想有没有没有其它的软件有这个功能,如果有,查看它的源代码就可以了,然后定制自己需要的功能。
3.多想多看多做,学习技术的不二法门。
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;
}