CPU Info: Debian Lenny x86
I am trying to use the output of top to return cpu usage.
- Im am actually trying to find a simple solution to gather cpu and mem usage, I have found top is the simplest to me.
My code works great when I run it from main, however as soon as my process forks to the background when the below code runs it does not work anymore.
Any clues why it acts differently from forked vs non forked?
Thanks
Expand|Select|Wrap|Line Numbers
- system("top -n 2 >& /var/tmp/topCpu");
- FILE *pfp;
- char line[100];
- string line2;
- string per = "";
- if ((pfp = fopen("/var/tmp/topCpu", "r")) == NULL) {
- fprintf(stderr, "POPEN Error\n");
- exit(1);
- }
- for (fgets(line, sizeof (line), pfp); fgets(line, sizeof (line), pfp);) {
- line2 = line;
- size_t found;
- found = line2.find("Cpu(s):");
- if(found < line2.length()){
- per = "";
- for(int i=0;i<strlen(line);i++){
- if(i >= 27 && i <= 32 && line[i] != '%'){
- per += line[i];
- }
- }
- }
- }
- fclose(pfp);
- return atof(per.c_str());