Skip to content
Advertisement

Using a shell commands in c++

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?

Advertisement

Answer

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)"")
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement