在c ++中使用shell命令

时间:2015-10-14 08:05:44

标签: c++ linux bash shell escaping

这是一个终端命令:

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

这是我的代码:

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;

以上代码在运行时会返回以下消息:

sh: 1: Syntax error: "(" unexpected

如何放置'/'符号,以使此命令正常工作?

1 个答案:

答案 0 :(得分:3)

您的问题不在C ++中。您正在使用popen调用您的命令,并且popensh shell中运行您的命令,该命令不支持<()语法,而在您的终端中您正在{{1} }},bash或任何其他支持zsh语法的shell。

编辑:更好的选择!使用烟斗!

<()

原始回答,无效!:尝试在popen("free -m | awk ...") 中调用bash

popen

代码:

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