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;
}