c++中如何异步执行cmd命令并获取结果

avatar
作者
猴君
阅读量:0

在C++中,你可以使用std::futurestd::async来实现异步执行命令并获取结果

#include<iostream> #include <future> #include <cstdio> #include<string> #include <stdexcept>  std::string exec_cmd(const std::string& cmd) {     char buffer[128];     std::string result;     FILE* pipe = popen(cmd.c_str(), "r");     if (!pipe) throw std::runtime_error("popen() failed!");     try {         while (fgets(buffer, sizeof buffer, pipe) != nullptr) {             result += buffer;         }     } catch (...) {         pclose(pipe);         throw;     }     pclose(pipe);     return result; }  int main() {     // 定义一个异步任务,执行命令 "ls" 并获取结果     std::future<std::string> future_result = std::async(std::launch::async, exec_cmd, "ls");      // 在此处执行其他任务...      // 获取异步任务的结果     std::string result = future_result.get();      // 输出结果     std::cout << "Command output: "<< std::endl<< result<< std::endl;      return 0; } 

这个示例中,我们首先定义了一个名为exec_cmd的函数,该函数接受一个字符串参数(要执行的命令),然后使用popen()函数执行该命令。popen()函数返回一个文件指针,我们可以从中读取命令的输出。我们将输出读入缓冲区并将其添加到结果字符串中,直到没有更多的输出可读。最后,我们使用pclose()关闭文件指针。

main()函数中,我们创建了一个std::future对象,该对象表示一个异步任务。我们使用std::async函数启动异步任务,该任务执行exec_cmd函数并传递要执行的命令(在本例中为ls)。

然后,我们可以在此处执行其他任务,而异步任务在后台运行。当我们需要获取异步任务的结果时,我们调用future_result.get()。这将阻塞,直到异步任务完成,并返回结果字符串。

请注意,这个示例仅适用于Unix-like系统(如Linux和macOS)。如果你正在使用Windows系统,你需要使用_popen()_pclose()函数替换popen()pclose()函数。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!