0

Hi,

Below command will give the cpu and memory usage of process in terms of percentage.
can we achieve same usin c/c++ API.

ps -C <process name> -o %cpu,%mem | tail -n 2

3
Contributors
3
Replies
17
Views
5 Months
Discussion Span
Last Post by can-mohan
0

There's a beautiful thing about Linux I think you should know. It's this. Almost all the apps that come with Linux have source code.

Let's say you want to incorporate what ps does into your app. The ps source code is open for you to see how it was done!

Example: https://github.com/soarpenguin/procps-3.0.5

Caveat. Your distro may have another source so use that instead.

Edited by rproffitt: Spelling

0

You can do that. OR since you already know the exact command already, you can use C++ to execute that command exactly and do whatever you need to do to get the output where you want it to go (STDOUT or wherever) using the system command, popen, execvp, pipes, whatever. popen is easy so use that unless there is a reason not to. See code below adapted to your line where "codeblocks" is the process.

#include <iostream>
#include <stdio.h>

using namespace std;

int main() {
    FILE *in;
    char buff[512];

    if(!(in = popen("ps -C codeblocks -o %cpu,%mem | tail -n 2", "r"))){
        return 1;
    }

    while(fgets(buff, sizeof(buff), in)!=NULL){
        cout << buff;
    }
    pclose(in);

    return 0;
} 

Code is from here. I simply replaced the command to be executed.

http://www.sw-at.com/blog/2011/03/23/popen-execute-shell-command-from-cc/

0

Hi,
I am doing in same manner , but i was told to use API's instead of command processing. i have been asked to check the same in boost similar to getrusage() API.

Edited by can-mohan: typo

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.