In Linux, if you want to monitor the operation of a process, such as viewing its CPU usage and memory usage, you need to read some system information from the system's/proc directory. Then the analysis results, especially in the embedded application This function is very important. The code in this article is obtained from the source analysis of the top command and has been partially modified and passed in fc6+gcc4.1 debugging. From this project I also gain some sentiment.
1. The Linux system is elegant, and if you do this in Windows, you need to invoke the ActiveX control. In Linux, you only need to read the text.
2. what function do you want to accomplish, if you do not know how to do, I would like to have no other software has this function, if there is, to view its source code can be, and then customize their own needs of the function.
3. Want to see more and do more, learn the begotten of technology.
Top command source code download: http://www.groupsys.com/top/download.shtml
Project Download: Http://www.cppblog.com/Files/dyj057/mytop.zip
Here is the code to get the system's CPU and memory conditions:
void Get_system_info (info) struct System_info * info;
{char buffer[4096 + 1];
int Fd,len;
char * p;
int i;
/* Getloadaverages/{FD = open ("Loadavg", o_rdonly);
Len = Read (fd,buffer, sizeof (buffer)-1);
Close (FD);
Buffer[len] = ';
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);
/* Skiprunning/tasks * p = SKIP_WS (p);
if (* p) info-> last_pid = atoi (p);
else info-> last_pid =-1;
}/* Getthecputimeinfo */{FD = open ("stat", o_rdonly);
Len = Read (fd,buffer, sizeof (buffer)-1);
Close (FD);
Buffer[len] = '; 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); /* Convertcp_timecounTstopercentages * * Percentages (4, Cpu_states,cp_time,cp_old,cp_diff);
}/* Getsystemwidememoryusage */{char * p;
FD = open ("Meminfo", o_rdonly);
Len = Read (fd,buffer, sizeof (buffer)-1);
Close (FD);
Buffer[len] = ';
/* bepreparedforextracolumnstoappearbeseeking toendsoflines * * p = buffer;
p = Skip_token (p); memory_stats[0] = Strtoul (p, & P, 10);
/* TotalMemory * p = STRCHR (P, ');
p = Skip_token (p); memory_stats[1] = Strtoul (p, & P, 10);
/* Freememory * p = STRCHR (P, ');
p = Skip_token (p); memory_stats[2] = Strtoul (p, & P, 10);
/* Buffermemory * p = STRCHR (P, ');
p = Skip_token (p); memory_stats[3] = Strtoul (p, & P, 10);
/* cachedmemory * * for (i = 0; i < 8; i + +) {p + +;
p = STRCHR (P, ');
} p = Skip_token (p); memory_stats[4] = Strtoul (p, & P, 10);
/* Totalswap * p = STRCHR (P, '); p = skip_toKen (P); memory_stats[5] = Strtoul (p, & P, 10);
/* Freeswap * * setarraysandstrings/info-> cpustates = cpu_states;
Info-> memory = memory_stats; }