can-mohan 0 Junior Poster

Hi All,

In below code i am getting ouput of process (based on name) memory and cpu utilization % using command "ps -C gnome-terminal -o %cpu,%mem | tail -n +2" .Here gnome-terminal is name of process for that i am printing these values. Now i want to implement the same by reading all the process name dynamically and passing to input to my function GetStdoutFromCommand instead of hardcoding in command. Can somebody throw some light on this , how to achieve the same by referring below code.
so basicallly in my command instead of giving hardcoded process name [i.e. gnome-terminal] i want to populate dynamically process name through array of strings or vector under double quotes and want to execute the same so that instead of one hardcoded process i will have ouptut of n number of dynamically populated process in under quotes .

"ps -C gnome-terminal -o %cpu,%mem | tail -n +2" needs to be replaced with "ps -C [[dynamically populated name of process] -o %cpu,%mem | tail -n +2"

    #include <iostream>
     #include <stdio.h>
     #include <stdlib.h>
    #include <sstream>
        using namespace std;

        string GetStdoutFromCommand(string cmd) {

        string data;
        FILE * stream;
        const int max_buffer = 256;
        char buffer[max_buffer];
        stream = popen(cmd.c_str(), "r");
        if (stream) {
        while (!feof(stream))
        if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer);
        pclose(stream);
        }
        return data;
        }

        int main (){
        float data [2];
        float a1,b1;
       string ls = GetStdoutFromCommand("ps -C gnome-terminal -o %cpu,%mem | tail -n +2");

        stringstream ss(ls);

        for(int i=0;i<2;i++)
            {
               ss>>data[i];
               cout<<data[i]<<endl;
            }

    cout << "LS: " << ls << endl;

        return 0;
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.