【问题标题】:Using a shell commands in c++在 C++ 中使用 shell 命令
【发布时间】:2016-01-12 05:18:54
【问题描述】:

这是一个终端命令:

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

如何放置“/”符号以使该命令正常工作?

【问题讨论】:

  • 看起来像默认 shell - sh - 不支持 &lt;(free -m) 语法。考虑调用bash
  • 在终端这个命令看起来不错
  • 你的终端shell可以是bash,它支持这个语法,而popen运行在sh,更原始的低级shell。试试echo $0。我刚刚尝试在 sh 中运行您的命令,但失败并显示相同的消息。

标签: c++ linux bash shell escaping


【解决方案1】:

您的问题不在 C++ 中。您正在使用popen 调用您的命令,而popen 在不支持&lt;() 语法的sh shell 中运行您的命令,而在您的终端中,您拥有bashzsh 或任何其他shell ,确实支持&lt;() 语法。

编辑:更好的选择!使用管道!

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

原始答案,无效!:尝试在popen 中调用bash

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

在代码中:

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

【讨论】:

  • 内存:3398 2848 550 380 209 959 {print $4} 不起作用
  • 为我工作(我刚刚将Mem 更改为Пам,因为我正在运行俄语本地化)。我添加了一个新选项来回答,看看吧。
  • 我也用过。但最好的,我看到的是Память: 3398 2785 613 339 212 918
  • 好的,我明白了,我原来的答案是错误的,使用管道选项
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
  • 2012-09-17
  • 2014-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多