Outputing top to a file from a forked process

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kardon33
    New Member
    • May 2007
    • 158

    #1

    Outputing top to a file from a forked process

    Hello Bytes,

    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

    Code:
        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());
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    I suspect you want to run your CPU usage on a separate thread rather than a separate process. That is, pthread instead of fork.

    I think you are getting the CPU usage of the process but not the process with your main().

    Comment

    • kardon33
      New Member
      • May 2007
      • 158

      #3
      No, i am not trying to get the cpu usage of any process but the entire system.

      I am getting gibberish when ran from process not still active in stdin. But I cant figure out why.

      Comment

      Working...