在 C++ 中使用 shell 命令
Using a shell commands in c++
这是一个终端命令:
awk '/^Mem/ {print }' <(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 \"\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;
以上代码,当运行、returns这条消息时:
sh: 1: Syntax error: "(" unexpected
如何放置“/”符号才能使此命令正常工作?
您的问题不在 C++ 中。您正在使用 popen
调用您的命令,并且 popen
在 sh
shell 中运行您的命令,该命令不支持 <()
语法,而在您的终端中bash
、zsh
或任何其他支持 <()
语法的 shell。
编辑:更好的选择!使用管道!
popen("free -m | awk ...")
原始答案,无效!:尝试在popen
中调用bash
:
bash -c "awk '/^Mem/ {print }' <(free -m)"
在代码中:
popen("bash -c \"awk '/^Mem/ {print }' <(free -m)\"")
这是一个终端命令:
awk '/^Mem/ {print }' <(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 \"\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;
以上代码,当运行、returns这条消息时:
sh: 1: Syntax error: "(" unexpected
如何放置“/”符号才能使此命令正常工作?
您的问题不在 C++ 中。您正在使用 popen
调用您的命令,并且 popen
在 sh
shell 中运行您的命令,该命令不支持 <()
语法,而在您的终端中bash
、zsh
或任何其他支持 <()
语法的 shell。
编辑:更好的选择!使用管道!
popen("free -m | awk ...")
原始答案,无效!:尝试在popen
中调用bash
:
bash -c "awk '/^Mem/ {print }' <(free -m)"
在代码中:
popen("bash -c \"awk '/^Mem/ {print }' <(free -m)\"")