3

Here's a terminal command:

awk '/^Mem/ {print $4}' <(free -m)

Here's my code:

class CSystemInfo{
public:
    std::string free_ram(){
        std::string s;
        FILE *in;
        char buff[512];
        //here is a prepared string (but with an error)
        if(!(in = popen("awk '/^Mem/ {print $4 \"\\t\"}' <(free -m)","r"))){
        return "";  
        }
        while(fgets(buff, sizeof(buff), in)!=NULL){
            cout << s;
            s=s+buff;
        }
        pclose(in);
        return s;
       }
};
    CSystemInfo info;
    std::string ram = info.free_ram();
    cout << ram;

The above code, when run, returns this message:

sh: 1: Syntax error: "(" unexpected

How can I place the '/' symbol, for this command to work correctly?

3
  • 1
    Looks like default shell - sh - is not supporting <(free -m) syntax. Consider invoking bash. Commented Oct 14, 2015 at 8:14
  • in terminal this command looks nice Commented Oct 14, 2015 at 8:16
  • Your teminal shell could be bash that supports this syntax, while popen runs in sh, more primitive, low-level shell. Try echo $0. I have just tried running your command in sh, it failed with the same message. Commented Oct 14, 2015 at 8:20

1 Answer 1

3

Your problem is not in C++. You are invoking your command with popen, and popen runs your command in sh shell, that does not support <() syntax, while in your terminal you are having bash, zsh or any other shell, that does support <() syntax.

Edit: Better choise! Use pipes!

popen("free -m | awk ...")

Original answer, not working!: Try invoking bash in popen:

bash -c "awk '/^Mem/ {print $4}' <(free -m)"

in code:

popen("bash -c \"awk '/^Mem/ {print $4}' <(free -m)\"")
Sign up to request clarification or add additional context in comments.

4 Comments

Memory: 3398 2848 550 380 209 959 {print $4} doesn't work
Works for me (I just changed Mem to Пам because I'm running russian localization). I added one new option to answer, check it out.
I use it too. But the best, what I see is Память: 3398 2785 613 339 212 918
OK, I see, my original answer is wrong, use pipe option

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.