Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 640
Максим Максимов Avatar asked Dec 27 '25 18:12

Максим Максимов


1 Answers

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)\"")
like image 109
Lapshin Dmitry Avatar answered Dec 31 '25 00:12

Lapshin Dmitry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!