[英]What is the proper way to execute a complex shell command within C++?
我一直在使用類似於此示例的代碼來從C ++中將結果獲取到Linux Shell命令。 使用基本命令似乎效果很好。 但是,當我嘗試使用示例中的命令運行它時,出現外殼錯誤:意外標記'('附近的語法錯誤
#include <stdio.h>
#include <iostream>
int main(int argc, char *argv[]) {
std::string cmdString = "cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | "
"awk -v RS=\"\" '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5) }' 2>&1";
std::string result, file;
FILE *stream;
std::cout << "cmdString = " << cmdString << std::endl;
stream = popen(cmdString.c_str(), "r");
char buffer[256];
if(fgets(buffer, sizeof(buffer), stream) != NULL) {
file = buffer;
result += file.substr(0, file.size() - 1);
}
pclose(stream);
std::cout << "result = " << result << std::endl;
return 0;
}
難道我做錯了什么? 我是否需要以某種方式重新格式化字符串?
您在命令行中使用bash
特定的構造。 POSIX要求將popen
的參數傳遞給bin/sh
,而不是用戶當前的shell。
要解決此問題,您可以執行以下任一操作:
/bin/sh
兼容。 bash
: std::string cmdString = "bash -c \\".....\\"";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.