我正在尝试实时显示命令的结果。我已经能够检索结果,但是我想直播。每当我在代码中放入while循环以重复该命令时,就会打开一个窗口,执行该命令,然后关闭该窗口,然后再打开另一个窗口,然后重复该过程,直到程序崩溃为止。我希望命令提示符在接收命令时在后台运行,因为我正在其前面运行QT gui。
这是我当前的代码:
cmd = _popen("snmpget -v 2c -c public 192.168.127.101 .1.3.6.1.4.1.8691.8.4.6.1.1.3.1.1.4.1", "r"); //input command in format (snmp_function -v version -c community_string IP_address OID)
if (cmd == NULL)
{
perror("_popen");
exit(EXIT_FAILURE);
}
while (fgets(result, sizeof(result), cmd)) //gets full responce string to snmpget and passes string to result variable
{
std::string str = result; //sets string to values in variable result
std::regex rgx("\"([^\"]*)\""); //retrieves only the section of the output string that is between double air quotes
std::smatch match;
std::string buffer;
std::stringstream ss(str);
std::vector<std::string> strings;
//necessary? whitespace
while (ss >> buffer)
strings.push_back(buffer);
for (auto& i : strings)
{
if (std::regex_match(i, match, rgx))
{
std::ssub_match submatch = match[1];
std::string str = submatch.str();
for (size_t j=0; j<str.length(); j++)
{
output[j] = str[j];
}
}
}
}
_pclose(cmd);
std::string
只是为了获得我想要的部分返回值。
通常,我可以通过在包含此内容的getchar()
循环的末尾放置一个while
来保持窗口打开,但是我不想依靠用户按Enter来获取更新的结果
答案 0 :(得分:0)
我建议您在执行第一个命令时使用嵌套的cmd。像这样:
cmd.exe /c cmd.exe /k "Put the command you want to execute here!"
我不确定是否需要使用引号,但是我知道它确实可以使用引号,因此这意味着您将第一行更改为:
cmd = _popen("cmd.exe /c cmd.exe /k \"snmpget -v 2c -c public 192.168.127.101 .1.3.6.1.4.1.8691.8.4.6.1.1.3.1.1.4.1\"", "r"); //Note the escaped quotes
以上内容未经测试,但我相信它可以为您带来预期的结果。请注意,这每次都会打开一个内部cmd,因此使用此解决方案,您可能需要跟踪出口。基本上,对于不是第一个命令的每个命令,您都需要发送出口以关闭该inner-> inner cmd。